App.js 4.29 KB
import './normal.css';
import './App.css';
import './color_theme_1.css';
import { useState, useEffect } from 'react';
import SideMenu from './SideMenu'
import ChatBox from './ChatBox'

function App() {

  useEffect(() => {
    getEngines();
  }, [])

  const [chatInput, setChatInput] = useState("");
  const [models, setModels] = useState([]);
  const [temperature, setTemperature] = useState(0.7);
  const [currentModel, setCurrentModel] = useState("text-davinci-003");
  const [chatLog, setChatLog] = useState([{
    user: "gpt",
    message: "Welcome to AI-PRO... How can I help you?"
  }]);

  // clear chats
  function clearChat(){
    setChatLog([]);
  }

  function getEngines(){
    fetch(process.env.REACT_APP_SERVER_URL + "/models")
    .then(res => res.json())
    .then(data => {
      // console.log(data.models.data)
      // set models in order alpahbetically
      data.models.data.sort((a, b) => {
        if(a.id < b.id) { return -1; }
        if(a.id > b.id) { return 1; }
        return 0;
      })
      setModels(data.models.data)
    })
  }

  async function handleSubmit(e){
    e.preventDefault();
    // console.log(chatInput)
    const userInput = ['what', 'why', 'when', 'where' , 'which', 'did', 'do', 'how', 'can', 'are', 'who', 'hey'];
    const userInputRegex = new RegExp(`\\b(${userInput.join('|')})\\b`, 'gi');
    const inputMatches = chatInput.match(userInputRegex);

    const userPunctuation = ['.', '?', '!', ':', ';', ','];
    const userPunctuationRegex = new RegExp(`${userPunctuation.join('')}$`, 'gi');
    const punctuationMatches = chatInput.match(userPunctuationRegex);

    // console.log(punctuationMatches)
    var userModifiedInput = chatInput

    if (!punctuationMatches) {
      if (!inputMatches) {
        userModifiedInput = chatInput + ".";
        // console.log("not a question!")
      } else {
        userModifiedInput = chatInput + "?";
        // console.log("its a question!")
      }
    }

    let chatLogNew = [...chatLog, { user: "me", message: `${userModifiedInput}`} ]
    setChatInput("");
    setChatLog(chatLogNew)

    // fetch response to the api combining the chat log array of messages and seinding it as a message to localhost:3000 as a post
    const messages = chatLogNew.map((message) => message.message).join("\n")

    const response = await fetch(process.env.REACT_APP_SERVER_URL + "/api", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        message: messages,
        currentModel,
       })
      });
    const data = await response.json();
    const parsedData = data.message.trim();
    // console.log(parsedData)
    const programmingKeywords = ['code', 'application', 'controller', 'rails' , 'PHP', 'java', 'javascript', 'script', 'console', 'python', 'programming', 'table'];

    const regex = new RegExp(`\\b(${programmingKeywords.join('|')})\\b`, 'gi');
    // console.log(regex)
    const matches = parsedData.match(regex);
    // console.log(matches);
    if (!matches) {
      var replaceTags = (parsedData.replace(/(?:\r\n|\r|\n)/g, '<br>').replace(/\./g, '. '))
      // console.log("not programming!")
    } else {
        replaceTags = (parsedData.replace(':',':<code>').replace('<?','&#60;?').replace('?>','?&#62;').replace(/\n/g, '<br>'))
      // console.log("programming!")
      //.replace('<?','&#60;' + '?').replace('?>','?'+'&#62;')
    }
    setChatLog([...chatLogNew, { user: "gpt", message: `${replaceTags}`} ])

    // setChatLog([...chatLogNew, { user: "gpt", message: `<div>${parsedData}</div>`} ])
    var scrollToTheBottomChatLog = document.getElementsByClassName("chat-log")[0];
    scrollToTheBottomChatLog.scrollTop = scrollToTheBottomChatLog.scrollHeight;
  }

  function handleTemp(temp) {
    if(temp > 1){
      setTemperature(1)
    } else if (temp < 0){
      setTemperature(0)
    } else {
      setTemperature(temp)
    }

  }

  return (
    <div className="App">
      <SideMenu
        currentModel={currentModel}
        setCurrentModel={setCurrentModel}
        models={models}
        setTemperature={handleTemp}
        temperature={temperature}
        clearChat={clearChat}
      />
      <ChatBox
        chatInput={chatInput}
        chatLog={chatLog}
        setChatInput={setChatInput}
        handleSubmit={handleSubmit} />
    </div>
  );
}


export default App;