sniro23's picture
Fix: Final deployment fix for processing_time error and restored app
a8406a1
raw
history blame
2.56 kB
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 ChatInterface format
const gradioHistory = history.map(msg => [
msg.role === 'user' ? msg.content : '',
msg.role === 'assistant' ? msg.content : ''
]).filter(pair => pair[0] || pair[1]);
const response = await fetch(`${HF_API_URL}/call/predict`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: [input, gradioHistory]
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return {
answer: data.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,
};
}