File size: 2,824 Bytes
01f0120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8406a1
01f0120
 
 
 
 
f0dba11
 
 
 
 
 
 
 
 
4addc11
01f0120
 
 
 
a8406a1
f0dba11
 
 
4addc11
a8406a1
01f0120
33cb5fa
01f0120
33cb5fa
01f0120
33cb5fa
 
01f0120
 
f0dba11
a8406a1
01f0120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
  };
}