tobeken / experience01

0 stars 0 forks source link

遅延推薦実装 #13

Closed tobeken closed 3 months ago

tobeken commented 3 months ago

遅延推薦は,事前タスクで得た平均値を取得し,システム応答終了のステータスを取ってから,カウントを開始し,その時間が,平均値を超えた場合に,プロンプトで思いつかないので.観点推薦をしてくださいを投げるようにする.

tobeken commented 3 months ago

2回連続でAPIが投げられる 途中でタスクが終わった場合.次のタスクで,観点推薦から始まってしまう. APIを叩くタイミングに関しては要検討. 157行目

// 5秒間ユーザ発話がなければ自動的にchatgpt_auto_recommendのAPIを呼び出す
    useEffect(() => {
      let autoRecommendTimer: NodeJS.Timeout;

      const checkAutoRecommend = async () => {
        const userDocRef = doc(db, "users", userId);
        const userSnapshot = await getDoc(userDocRef);
        const userData = userSnapshot.data();

        if (userData && userData.groupNumber >= 7 && userData.groupNumber <= 9) {
          autoRecommendTimer = setTimeout(async () => {
            if (!transcript  && !autoRecommendCalled  && !isBotResponding) {
              setAutoRecommendCalled(true); // API呼び出しフラグを設定auto_recommend';
              const apiUrl = '/api/openai/chatgpt_auto_recommend'; 
              const body = JSON.stringify({ text: '', history });

              try {
                const response = await fetch(apiUrl, {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/json',
                  },
                  body,
                });

                const response_data = await response.json();
                const botres = response_data.airesponse;

                if (botres) {
                  const userDocRef = doc(db, "users", userId);
                  const roomsCollectionRef = collection(userDocRef, "rooms");
                  const roomDocRef = doc(roomsCollectionRef, selectedRoom ?? "defaultRoom");
                  const messageCollectionRef = collection(roomDocRef, "messages");

                  const botMessageRef = await addDoc(messageCollectionRef, {
                    text: botres,
                    sender: "bot",
                    createdAt: serverTimestamp(),
                    endTime: null,
                  });

                  setHistory(prevHistory => [...prevHistory, { role: 'assistant', content: botres }]);

                  const body = JSON.stringify({ text: botres });
                  const response = await fetch('/api/openai/tts', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json',
                    }, body,
                  });

                  if (!response.ok) {
                    throw new Error('レスポンスがネットワーク問題により再生できません.');
                  }

                  const blob = await response.blob();
                  const url = URL.createObjectURL(blob);
                  const audio = new Audio(url);

                  setIsBotResponding(true);
                  audio.play();
                  botStartTime = Timestamp.now();
                  await setDoc(botMessageRef, { createdAt: botStartTime }, { merge: true });

                  audio.addEventListener('ended', async () => {
                    botEndTime = Timestamp.now();
                    await setDoc(botMessageRef, { endTime: botEndTime }, { merge: true });
                    setIsBotResponding(false);
                  });
                }
              } catch (error) {
                console.log(error);
              }
            }
          }, 5000);
        }
      };

      if (botEndTime) {
        setAutoRecommendCalled(false); // botEndTimeが更新されるたびにリセット
        checkAutoRecommend();
      }
      return () => clearTimeout(autoRecommendTimer);
    }, [botEndTime, transcript, history, selectedRoom, userId,isBotResponding]);