Code viewer for World: Weather Chatbot
document.write(`

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <style>
    body {
      font-family: 'Helvetica Neue', sans-serif;
      background-color: #f7f7f7;
      color: #333;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
    }

    h1 {
      font-family: 'Roboto', sans-serif;
      color: #007bff;
      margin-bottom: 20px;
      font-weight: 700;
    }

    input {
      width: calc(100% - 20px);
      padding: 10px;
      margin-bottom: 10px;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 5px;
      box-sizing: border-box;
    }

    button {
      width: calc(100% - 20px);
      padding: 10px;
      font-size: 16px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    input,
    button {
      transition: background-color 0.3s ease;
    }

    button:hover {
      background-color: #0056b3;
    }

    #enterkey {
      margin-bottom: 20px;
      width: 80%;
      max-width: 400px;
    }

    #prompt-container,
    #response-container,
    #weather-container {
      width: 80%;
      max-width: 400px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      border-radius: 10px;
      margin: 20px;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #ddd;
    }

    #response-container {
      background-color: #ffffcc;
    }

    p {
      font-style: italic;
      font-size: 14px;
    }
  </style>

  <h1> Chat with GPT model </h1>
  <p>You enter your API key below and then chat away. ... </p>
  <div id=enterkey>
    Enter API key: 
    <input style='width:100%;' maxlength='2000' NAME="apikey" id="apikey" VALUE=''>
    <button onclick='setkey();' class=ab-normbutton >Set API key</button>
  </div>
  <div id="prompt-container">
    <h3>Enter a "prompt"</h3>
    <input style="width:100%;" id="me" value="Hello World!">
    <button onclick="sendchat();" class="ab-normbutton">Send</button>
  </div>
  <div id="response-container">
    <h3>GPT replies</h3>
    <div id="them"></div>
  </div>
<div id="weather-container">
  <h3>Weather Information</h3>
  Enter Location: <input style="width:100%;" id="location" value="City, Country">
  <button onclick="getWeather();" class="ab-normbutton">Get Weather</button>
  <div id="weather-response"></div>
</div>
  <p><i>Be warned that GPT replies are often completely inaccurate. ... </i></p>
  <pre></pre>
`);

var apikey = "";
var theprompt = "Hello World!";

    function setkey() {
      apikey = document.getElementById("apikey").value.trim();
      if (apikey !== "") {
        document.getElementById("enterkey").innerHTML = "<b>API key has been set successfully.</b>";
      } else {
        document.getElementById("enterkey").innerHTML = "<font color=red><b>Please enter a valid API key.</b></font>";
      }
    }

    function sendchat() {
      theprompt = document.getElementById("me").value.trim();

      var thedata = {
        "model": "gpt-3.5-turbo",
        "temperature": 0.7,
        "messages": [{
          "role": "user",
          "content": theprompt
        }]
      };

    // MH edit
    console.log ( "Sending to GPT: " + theprompt );

      var thedatastring = JSON.stringify(thedata);

      axios.post("https://api.openai.com/v1/chat/completions", thedatastring, {
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + apikey
        }
      })
      .then(function (response) {
        successfn(response.data);
      })
      .catch(function (error) {
        errorfn();
      });
    }

    function successfn(data) {
      var answer = data["choices"][0].message.content;
      document.getElementById("them").innerHTML = answer;
    }

    function errorfn() {
      if (apikey === "") {
        document.getElementById("them").innerHTML = "<font color=red><b>Enter API key to be able to chat.</b></font>";
      } else {
        document.getElementById("them").innerHTML = "<font color=red><b>An error occurred. Please try again.</b></font>";
      }
    }

    function getWeather() {
      const location = document.getElementById("location").value;
      const openAIPrompt = `What is the weather like in ${location} today?`;

      callOpenAPI(openAIPrompt)
        .then(function (openAIResponse) {
          const openAILocation = getLocationFromOpenAIResponse(openAIResponse);
          return callOpenWeatherAPI(openAILocation);
        })
        .then(function (openWeatherResponse) {
          document.getElementById("weather-response").innerText = openWeatherResponse;
        })
        .catch(function (error) {
          console.error('Error:', error);
          document.getElementById("weather-response").innerText = `Error getting weather information: ${error.message}`;
        });
    }

    async function callOpenAPI(prompt) {
      const openAIKey = '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';
      const openAIURL = 'https://api.openai.com/v1/chat/completions';

      const data = {
        model: 'gpt-3.5-turbo',
        temperature: 0.7,
        messages: [{
          role: 'user',
          content: prompt
        }]
      };

    // MH edit
    console.log ( "Sending to GPT: " + prompt );

      const response = await axios.post(openAIURL, data, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${openAIKey}`
        }
      });

    // MH edit
    console.log ( response.data.choices[0].message.content );
    
      return response.data.choices[0].message.content;
    }

async function callOpenWeatherAPI(lat, lon) {
  try {
    // Use OpenWeather API to get the weather information for the specified location
    const openWeatherKey = 'ee369e8f6d7b5ecdfd119ca15c27d49a'; // Replace with your actual API key
    const openWeatherURL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${openWeatherKey}`;

    // MH edit
    console.log ( "Sending to OpenWeather: " + openWeatherURL );

    const response = await axios.get(openWeatherURL);

    // Extract the weather information from the response
    const weatherDescription = response.data.weather[0].description;
    const temperatureKelvin = response.data.main.temp;
    
    // Convert temperature to Celsius
    const temperatureCelsius = temperatureKelvin - 273.15;

    return `Weather: ${weatherDescription}, Temperature: ${temperatureCelsius.toFixed(2)}°C`;
  } catch (error) {
    console.error('OpenWeather API Error:', error);
    throw error; // Re-throw the error to propagate it to the next catch block
  }
}

function getLocationFromOpenAIResponse(openAIResponse) {
      const words = openAIResponse.split(' ');
      return words[words.length - 1].replace('?', ''); // Remove any trailing question mark
    }