# Chat App

<script>


import OpenAI from "https://lively-kernel.org/lively4/lively4-core/demos/openai/openai.js"


const key = await OpenAI.ensureSubscriptionKey();
const url = "https://api.openai.com/v1/chat/completions";

//respons to the question
async function chat(text) {

  input.value = "";

  conversation.push({"role": "user", "content": text});

  let prompt = {
        "model": "gpt-3.5-turbo",
        "max_tokens": 500,
        "temperature": 0.1,
        "top_p": 1,
        "n": 1,
        "stream": false,
        "stop": "VANILLA",
        "messages": conversation,
      };


  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${key}`
    },
    body: JSON.stringify(proAmpt)
  };

  let result = await fetch(url, requestOptions).then(r=>r.json())
  conversation.push({"role": "system", "content": result.choices[0].message.content})
  
  responses.appendChild(<li><strong>You</strong></li>);
  responses.appendChild(<li style="margin-bottom:15px;">{text}</li>);
  
  responses.appendChild(<li><strong>AI</strong></li>);
  responses.appendChild(<li style="margin-bottom:15px;">{result.choices[0].message.content}</li>);
}


let responses = <ul style="list-style-type: none; height: 500px ; overflow-y: scroll"></ul>;

let conversation = [
  {
    role: 'system',
      content: ''
  }
];


let input = <input type="text" placeholder="Message ChatGPT" style="padding:15px; background-color:white; border: 1px solid lightgray; border-radius: 10px; width: 85%; bottom: 20px;">


</input>

input.addEventListener("keydown", function(event) {
    if (event.keyCode === 13) {
      chat(input.value);
    }
});

var ui = <div style="color:black; height:100%">
  {responses}
  {input}

</div>

ui

</script>