最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AI Bot with stopGenerating element - Stack Overflow

programmeradmin2浏览0评论

Hello im working on some project that includes AI. User send an message to AI API and AI response. This is not my problem it work very well. But we have some stop generating button. It's like the chatGPT when user touch to the Stop Generating button the response should be left incomplete and should appear like that in the ui. Like the bots message is "Hello!" but if user touch stop scrolling button ben index is in e letter it should be shown as "He". Actually it works too but i get the full message after. So both "He" and "hello!" are output in the ui. I just want "He" text. Can someone help me?

const connectSocket = async () => {
    try {
      const token = await AsyncStorage.getItem('userToken');
      if (!token) {
        console.log("JWT Token bulunamadı");
        return;
      }

      // Eğer önceki socket varsa temizle
      if (socketRef.current) {
        socketRef.current.removeAllListeners();
        socketRef.current.disconnect();
      }

      socket = io("/////", {
        extraHeaders: {
          Authorization: `Bearer ${token}`,
        },
      });

      socketRef.current = socket;

      socket.on('connect', () => {
        console.log("Socket bağlantısı başarılı");
        // Sadece mevcut bir chatId varsa odaya katıl
        if (currentChatId) {
          //console.log("Odaya katılınıyor:", currentChatId);
          socket.emit('join_chat', { chatId: currentChatId });
        }
      });

      socket.on('connect_error', (error) => {
        console.error('Socket bağlantı hatası:', error);
      });

      socket.on('ai_response', (data) => {
        if (data.message) {
          const { text, isUser, sendDate, chatId } = data.message;
          //console.log("AI yanıtı alındı:", {
          //  receivedChatId: chatId,
          //  currentChatId,
          //  isUser,
          //  messageLength: text.length
          //});
       
          // Sadece ilgili chat odasına ait mesajları işle
          if (chatId === currentChatId && !isUser) {
            //console.log("Mesaj işleniyor - Aynı oda ID'si");
            setIsTyping(true);
            setTypingText('');
            animateTyping(text);
          } else {
            console.log("Mesaj işlenmiyor - Farklı oda ID'si veya kullanıcı mesajı");
          }
        } else if (data.error) {
          console.log("AI yanıt hatası:", data.error);
          Toast.show({
            type: 'error',
            text1: 'Error',
            text2: data.error,
            position: 'bottom',
          });
        }
      });
    } catch (error) {
      console.error('Token yükleme hatası:', error);
    }
  };

  connectSocket();


  // Cleanup function - ekran kapandığında çalışır
  return () => {
    //console.log("Chat Detail Screen kapatılıyor");
    // Odadan çık
    if (socketRef.current && currentChatId) {
      //console.log("Odadan çıkış yapılıyor:", currentChatId);
      socketRef.current.emit('leave_chat', { chatId: currentChatId });
    }
    // Socket bağlantısını kapat
    if (socket) {
      //console.log("Socket bağlantısı kapatılıyor");
      socket.removeAllListeners();
      socket.disconnect();
    }
    if (socketRef.current) {
      socketRef.current.removeAllListeners();
      socketRef.current.disconnect();
    }
  };
}, [currentChatId]); // Sadece currentChatId değiştiğinde yeniden bağlan

const addMessage = (message, isUser, sendDate) => {
  const newMessage = {
    text: message,
    isUser: isUser,
    sendDate: sendDate || new Date().toISOString(),
  };

  setMessages((prevMessages) => [...prevMessages, newMessage]);
  setShowLogoAndBoxes(false);

  setTimeout(() => {
    scrollViewRef.current?.scrollToEnd({ animated: true });
  }, 100);
};

const sendMessage = async () => {
  const text = inputText.trim();
  if (!text) return;

  //console.log("Mesaj gönderme işlemi başlatıldı");
  const sendDate = new Date().getTime();
 
  // Eğer mevcut bir chatId yoksa, yeni bir chat oluştur
  let chatIdToUse = currentChatId;
  if (!chatIdToUse) {
    //console.log("Yeni chat oluşturuluyor");
    try {
      const token = await AsyncStorage.getItem('userToken');
      if (!token) {
        console.error('Token bulunamadı');
        return;
      }

      const chatData = {
        categoryId: categoryId,
        content: text
      };

      const response = await DatabaseManager.createChat(chatData, token);
      if (response.success) {
        chatIdToUse = response.data.chatId;
        setCurrentChatId(chatIdToUse);
        //console.log("Yeni chat oluşturuldu:", chatIdToUse);


        // Odaya katılma
        if (socketRef.current) {
          //console.log("Yeni odaya katılınıyor:", chatIdToUse);
          socketRef.current.emit('join_chat', { chatId: chatIdToUse });
          // Kısa bir bekleme süresi ekleyelim socket'in odaya katılması için
          await new Promise(resolve => setTimeout(resolve, 500));
          //console.log("Odaya katılma tamamlandı");
        }
      } else {
        console.error("Chat oluşturulamadı:", response.error);
        return;
      }
    } catch (error) {
      console.error("Chat oluşturma hatası:", error);
      return;
    }
  } else {
    console.log("Mevcut chat kullanılıyor:", chatIdToUse);
  }

  // Mesajı ekle ve socket üzerinden gönder
  addMessage(text, true, sendDate);
 
  const messageData = {
    message: {
      text: text,
      categoryId: categoryId,
      chatId: chatIdToUse,
      sendDate: sendDate
    }
  };

  //console.log('Socket üzerinden mesaj gönderiliyor:', messageData);
  if (socketRef.current) {
    socketRef.current.emit('send_message', messageData);
    //console.log("Mesaj gönderildi");
  } else {
    console.error('Socket bağlantısı bulunamadı');
    Toast.show({
      type: 'error',
      text1: 'Error',
      text2: 'Connection error. Please try again.',
      position: 'bottom',
    });
  }
  setInputText('');
};

const animateTyping = (text) => {
  setIsTyping(true);
  setTypingText('');
  let index = 0;
  let currentInterval = null;

  currentInterval = setInterval(() => {
    if (index < text.length && !stopGenerating) {
      setTypingText(prevText => {
        const newText = prevText + text[index];
        // Her karakter eklendiğinde scroll yap
        setTimeout(() => {
          scrollToBottom(true);
        }, 50);
        return newText;
      });
      index++;
    } else {
      clearInterval(currentInterval);
      setIsTyping(false);

      if (!stopGenerating) {
        const sendDate = new Date().toISOString();
        addMessage(text, false, sendDate);
      }
      setTypingText('');
      setStopGenerating(false);
    }
  }, 50);

  return () => {
    if (currentInterval) {
      clearInterval(currentInterval);
    }
  };
};

const handleStopGenerating = () => {
  console.log("Stop generating başlatıldı");
  setStopGenerating(true);
  setIsTyping(false);
 
  if (typingText) {
    console.log("Yarım kalan mesaj kaydediliyor");
    const sendDate = new Date().toISOString();
    addMessage(typingText, false, sendDate);
  }
  setTypingText('');
};


{isTyping && (
              <View style={styles.botMessageContainer}>
                <View style={styles.botMessage}>
                  <Text style={styles.botMessageText}>{typingText}</Text>
                </View>
                <View style={styles.actionButtons}>
                  <TouchableOpacity
                    onPress={() => copyToClipboard(typingText)}>
                    <CopyIcon
                      width={17}
                      height={17}
                      style={styles.actionIcon}
                    />
                  </TouchableOpacity>
                  <TouchableOpacity onPress={() => shareMessage(typingText)}>
                    <ShareIcon
                      width={17}
                      height={17}
                      style={styles.actionIcon}
                    />
                  </TouchableOpacity>
                </View>
              </View>
            )}
            {isTyping && (
              <TouchableOpacity
                style={styles.stopGeneratingButton}
                onPress={handleStopGenerating}>
                <View style={styles.stopGeneratingContent}>
                  <View style={styles.stopDot} />
                  <Text style={styles.stopGeneratingText}>
                    {t('Stop generating...')}
                  </Text>
                </View>
              </TouchableOpacity>
            )}

发布评论

评论列表(0)

  1. 暂无评论