File size: 13,572 Bytes
77db471
 
 
 
 
03c52a3
 
 
 
 
 
 
 
 
 
77db471
 
 
 
7317d80
a4b5dd8
 
03c52a3
 
 
 
 
 
a4b5dd8
77db471
8b2fcca
77db471
03c52a3
 
 
61ba0c6
03c52a3
 
 
 
61ba0c6
03c52a3
 
 
 
 
 
 
 
 
 
 
 
 
 
7317d80
03c52a3
 
 
7317d80
03c52a3
 
 
8b2fcca
a4b5dd8
8b2fcca
03c52a3
 
 
 
 
 
 
 
dd8b5df
03c52a3
 
dd8b5df
03c52a3
 
 
 
 
 
 
 
 
 
 
 
 
 
dd8b5df
03c52a3
 
 
7205808
8b2fcca
 
dd8b5df
a4b5dd8
 
03c52a3
 
a4b5dd8
8b2fcca
dd8b5df
03c52a3
 
a4b5dd8
03c52a3
 
 
 
 
 
 
 
 
 
 
 
a4b5dd8
03c52a3
a4b5dd8
 
03c52a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
032d01b
 
03c52a3
032d01b
 
 
 
 
 
03c52a3
032d01b
 
 
 
 
03c52a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd8b5df
 
8b2fcca
03c52a3
 
 
7317d80
03c52a3
 
 
 
 
 
 
8b2fcca
 
77db471
a4b5dd8
 
 
 
 
03c52a3
a4b5dd8
 
 
 
 
 
77db471
 
8b2fcca
 
 
77db471
8b2fcca
77db471
 
03c52a3
 
 
 
 
 
 
 
77db471
 
a4b5dd8
8b2fcca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41d60be
 
 
8b2fcca
42580a8
77db471
41d60be
a4b5dd8
03c52a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4b5dd8
 
 
 
 
 
 
fb65623
a4b5dd8
7317d80
8b2fcca
 
 
 
 
 
 
 
 
41d60be
 
8b2fcca
41d60be
8b2fcca
a4b5dd8
 
8b2fcca
41d60be
 
 
8b2fcca
 
 
41d60be
 
 
8b2fcca
 
41d60be
8b2fcca
a4b5dd8
03c52a3
41d60be
 
 
 
8b2fcca
 
 
41d60be
 
 
77db471
 
20bd18d
77db471
03c52a3
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import React, { useState, useRef, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import Avatar from './Avatar.jsx';
import '../App.css';

const ChatInterface = ({ 
  messages = [], 
  setMessages = () => {}, 
  onMessageSent = () => {}, 
  activeConversationId,
  saveBotResponse, 
  toLogin, 
  onNewChat = () => {},
  refreshConversationList = () => {} 
}) => {
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef(null);
  const textareaRef = useRef(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [tokenLimitReached, setTokenLimitReached] = useState(false);
  const [hasInteractionStarted, setHasInteractionStarted] = useState(false);
  const [currentStreamId, setCurrentStreamId] = useState(null);
  
  // Pour optimiser les performances du streaming
  const accumulatedText = useRef('');
  const updateThreshold = 1; 
  const updateIntervalRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  
  useEffect(() => {
    scrollToBottom();
    
    if (updateIntervalRef.current) {
      clearInterval(updateIntervalRef.current);
      updateIntervalRef.current = null;
    }
    
    if (isStreaming && currentStreamId) {
      updateIntervalRef.current = setInterval(() => {
        if (accumulatedText.current.length > 0) {
          setMessages(prev => {
            return prev.map(msg => 
              msg.id === currentStreamId 
                ? { ...msg, text: msg.text + accumulatedText.current } 
                : msg
            );
          });
          accumulatedText.current = '';
        }
      }, 100); 
    }
    
    return () => {
      if (updateIntervalRef.current) {
        clearInterval(updateIntervalRef.current);
      }
    };
  }, [isStreaming, currentStreamId, messages]);
  const sendMessage = async (message) => {
    try {
      setHasInteractionStarted(true);
      setIsLoading(true);
      const userMessageId = `user-${Date.now()}`;

      setMessages(prev => [...prev, { 
        sender: 'user', 
        text: message,
        id: userMessageId
      }]);      
      const updatedConversationId = await onMessageSent(message);
      
      const streamMessageId = `bot-${Date.now()}`;
    setCurrentStreamId(streamMessageId);
      
      setMessages(prev => {
        const userMessageExists = prev.some(m => m.id === userMessageId);
        
        const updatedMessages = userMessageExists ? prev : [
          ...prev, 
          { sender: 'user', text: message, id: userMessageId }
        ];
        
        return [...updatedMessages, { 
          sender: 'bot', 
          text: '', 
          id: streamMessageId 
        }];
      });
      
      setIsLoading(false);
      setIsStreaming(true); 
      
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ 
          message,
          conversation_id: activeConversationId || updatedConversationId,
          skip_save: false // Le backend gère la sauvegarde
        }),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        
        if (errorData.error === 'token_limit_exceeded') {
          setIsStreaming(false);
          setCurrentStreamId(null);
          setTokenLimitReached(true);
          
          setMessages(prev => [...prev.filter(m => m.id !== streamMessageId), { 
            sender: 'bot', 
            text: "⚠️ **Limite de taille de conversation atteinte**\n\nCette conversation est devenue trop longue. Pour continuer à discuter, veuillez créer une nouvelle conversation." 
          }]);
          
          return;
        }
        
        throw new Error(`Chat API error ${response.status}`);
      }
      
      if (response.headers.get('content-type')?.includes('text/event-stream') && response.body) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let fullText = '';
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n\n');
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(5));
                
                if (data.type === 'start') {
                  console.log("Début du streaming");
                  fullText = '';
                  accumulatedText.current = '';
                } 
                else if (data.type === 'end') {
                  console.log("SSE End received");
                  setIsStreaming(false);
                  setCurrentStreamId(null);
                  setIsLoading(false);
                  
                  setMessages(prev => 
                    prev.map(msg => 
                      msg.id === streamMessageId 
                        ? { ...msg, sender: 'bot', text: fullText }
                        : msg
                    )
                  );
                  
                  if (typeof refreshConversationList === 'function') {
                    setTimeout(refreshConversationList, 100);
                  }
                  
                  return; 
                }
                if (data.content) {
                      fullText += data.content;
                      
                      // Update immediately without accumulation
                      setMessages(prev => {
                        return prev.map(msg => 
                          msg.id === streamMessageId 
                            ? { ...msg, text: fullText }
                            : msg
                        );
                      });
                      
                      // Ensure scroll
                      requestAnimationFrame(scrollToBottom);
                    }
                else if (data.type === 'error') {
                  console.error("SSE Error received:", data.error);
                  setIsStreaming(false);
                  setCurrentStreamId(null);
                  setIsLoading(false);
                  
                  setMessages(prev => 
                    prev.map(msg => 
                      msg.id === streamMessageId 
                        ? { sender: 'bot', text: "Désolé, une erreur s'est produite." }
                        : msg
                    )
                  );
                }
              } catch (e) {
                console.error('Error parsing SSE data:', e, line);
              }
            }
          }
        }
      } 
      else {
        console.log("Received non-streaming response.");
        const responseData = await response.json();
        setIsStreaming(false);
        setCurrentStreamId(null);
        setIsLoading(false);
        
        setMessages(prev => 
          prev.map(msg => 
            msg.id === streamMessageId 
              ? { sender: 'bot', text: responseData.response, id: streamMessageId }
              : msg
          )
        );
        
        if (typeof refreshConversationList === 'function') {
          setTimeout(refreshConversationList, 100);
        }
      }
      
    } catch (error) {
      console.error('Erreur lors de l\'envoi/réception du message:', error);
      setIsStreaming(false);
      setCurrentStreamId(null);
      setIsLoading(false);
      
      setMessages(prev => {
        const filteredMessages = prev.filter(m => m.id !== currentStreamId);
        return [...filteredMessages, 
          { sender: 'bot', text: "Désolé, une erreur s'est produite. Veuillez réessayer." }
        ];
      });
    }
  };

  const handleCreateNewConversation = () => {
    onNewChat();
    setTokenLimitReached(false);
    setHasInteractionStarted(false);
  };
  
  useEffect(() => {
    if (activeConversationId === null && messages.length === 0) {
      setHasInteractionStarted(false);
    }
  }, [activeConversationId, messages]);

  const handleSubmit = (e) => {
    e.preventDefault();
    const txt = inputMessage.trim();
    if (!txt) return;
    sendMessage(txt);
    setInputMessage('');
    if (textareaRef.current) textareaRef.current.style.height = 'auto';
  };

  const isMarkdown = (text, sender) => {
    if (sender === 'bot') {
      return true;
    }
    return /(?:\*\*|__|##|\*|_|`|>|\d+\.\s|\-\s|\[.*\]\(.*\))/.test(text);
  };
  
  
  return (
    <div className="chat-container">
      {messages.length === 0 && !hasInteractionStarted ? (
        <>
          <div className="chat-header">
            <h2 className="chat-title">Medic.ial</h2>
            <Avatar onClick={toLogin} />
          </div>
          <div className="no-messages-view">
            <div className="welcome-content">
              <div className="welcome-message">
                <p>Bonjour ! Comment puis-je vous aider aujourd'hui ? 🧑‍⚕️</p>
              </div>
              <div className="input-container centered">
                <form onSubmit={handleSubmit} className="input-form">
                  <textarea
                    value={inputMessage}
                    onChange={(e) => setInputMessage(e.target.value)}
                    placeholder="Posez une question..."
                    disabled={isLoading}
                    rows="1"
                    ref={textareaRef}
                    className="input-textarea"
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        handleSubmit(e);
                      }
                    }}
                    onInput={(e) => {
                      e.target.style.height = 'auto';
                      e.target.style.height = `${e.target.scrollHeight}px`;
                    }}
                  />
                  <button type="submit" disabled={isLoading || !inputMessage.trim()}>
                    <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3">
                      <path d="M120-160v-240l320-80-320-80v-240l760 320-760 320Z"/>
                    </svg>
                  </button>
                </form>
              </div>
            </div>
          </div>
        </>
      ) : (
        <>
          <div className="chat-header">
            <Avatar onClick={toLogin} />
            <h2 className="chat-title">Medic.ial</h2>
          </div>
          <div className="messages-container">
          {messages.map((msg, index) => {
  const isActiveStreaming = isStreaming && msg.id === currentStreamId;
  
  return (
    <div key={msg.id || index} className={`message ${msg.sender}`}>
      <div className={`message-content ${isActiveStreaming ? 'streaming-message' : ''}`}>
        {isMarkdown(msg.text, msg.sender) ? 
          <ReactMarkdown>{msg.text}</ReactMarkdown> : 
          <span>{msg.text}</span>
        }
        {isActiveStreaming && (
          <span className="typing-indicator"></span>
        )}
      </div>
    </div>
  );
})}
            
            {tokenLimitReached && (
              <div className="token-limit-warning">
                <button 
                  className="new-conversation-button"
                  onClick={handleCreateNewConversation}
                >
                  Démarrer une nouvelle conversation
                </button>
              </div>
            )}
            
            {isLoading && (
              <div className="message bot">
                <div className="message-content loading">
                  <span>.</span><span>.</span><span>.</span>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
          <div className="input-container">
            <form onSubmit={handleSubmit} className="input-form">
              <textarea
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                placeholder={tokenLimitReached ? "Créez une nouvelle conversation pour continuer..." : "Tapez votre message ici..."}
                disabled={isLoading || tokenLimitReached}
                rows="1"
                ref={textareaRef}
                className="input-textarea"
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    handleSubmit(e);
                  }
                }}
                onInput={(e) => {
                  e.target.style.height = 'auto';
                  e.target.style.height = `${e.target.scrollHeight}px`;
                }}
              />
              <button type="submit" disabled={isLoading || !inputMessage.trim() || tokenLimitReached}>
                <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3">
                  <path d="M120-160v-240l320-80-320-80v-240l760 320-760 320Z"/>
                </svg>
              </button>
            </form>
            <figcaption className="disclaimer-text">
              Medic.ial est sujet à faire des erreurs. Vérifiez les informations fournies.
            </figcaption>
          </div>
        </>
      )}
    </div>
  );
};

export default ChatInterface;