The goal of this was to have another music recommendation system based on the response of chatgpt. The best way to do this is through the chatgpt api.

What the api needs

  • endpoint: https://api.openai.com/v1/chat/completions
  • API Key: you can generate a free one by creating a new openai account
  • model: I used gpt-3.5-turbo
  • headers:
    • 'Content-Type': 'application/json',
    • 'Authorization': authorizationHeader
  • messages: specify the role of the ai and the question of the user

Full Code (html and js)

<form id="userInputForm">
    <label for="userInput">Enter your music preference:</label>
    <input type="text" id="userInput" required>
    <button type="submit">Submit</button>
  </form>

  <div id="outputContainer"></div>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const userInputForm = document.getElementById('userInputForm');
    const userInputInput = document.getElementById('userInput');
    const outputContainer = document.getElementById('outputContainer');

    // Encode the API key using Base64
    const encodedApiKey = "encoded API Key";
    const decodedApiKey = atob(encodedApiKey);
    const authorizationHeader = 'Bearer ' + decodedApiKey;

    userInputForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      const userInput = userInputInput.value;
      userInputInput.value = '';

      try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
        messages: [
            { role: 'system', content: 'You are a user requesting music recommendations.' },
            { role: 'user', content: userInput }
        ],
        model: 'gpt-3.5-turbo' 
        }, {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': authorizationHeader
        }
        });

        const assistantReply = response.data.choices[0].message.content;
        displayAssistantReply(assistantReply);
      } catch (error) {
        console.error('Error calling ChatGPT API:', error);
        console.error('Error response:', error.response);
        console.error('Error message:', error.message);
        displayAssistantReply('Sorry, an error occurred while processing your request.');
        }
    });

    function displayAssistantReply(reply) {
      const replyElement = document.createElement('p');
      replyElement.textContent = 'Assistant: ' + reply;
      outputContainer.appendChild(replyElement);
    }
  </script>
</body>
</html>

In Depth

<form id="userInputForm">
    <label for="userInput">Enter your music preference:</label>
    <input type="text" id="userInput" required>
    <button type="submit">Submit</button>
  </form>

This piece of html takes in and stores the user input

<div id="outputContainer"></div>

This is the area where the api will output the response

// Encode the API key using Base64
const encodedApiKey = "encoded API Key";
const decodedApiKey = atob(encodedApiKey);
const authorizationHeader = 'Bearer ' + decodedApiKey;

Base64 the key so github won't complain lol

try {
    const response = await axios.post('https://api.openai.com/v1/chat/completions', {
    messages: [
        { role: 'system', content: 'You are a user requesting music recommendations.' },
        { role: 'user', content: userInput }
    ],
    model: 'gpt-3.5-turbo' 
    }, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': authorizationHeader
    }
    });

    const assistantReply = response.data.choices[0].message.content;
    displayAssistantReply(assistantReply);

This is the most important part of the code. These are the options that I had alluded to in the beginning of this blog

catch (error) {
    console.error('Error calling ChatGPT API:', error);
    console.error('Error response:', error.response);
    console.error('Error message:', error.message);
    displayAssistantReply('Sorry, an error occurred while processing your request.');
    }
});

Catches the errors. Outputs it onto html and in the console

function displayAssistantReply(reply) {
    const replyElement = document.createElement('p');
    replyElement.textContent = 'Assistant: ' + reply;
    outputContainer.appendChild(replyElement);
  }

If a response successfully is sent, it will be shown on the html

What this can be used for in the future

It can definitely be used to teach APIs! This is a topic students would be really interested in and want to implement on their own. The only problem is that everyone would need to create new accounts in order to use it. You could also just buy 5 dollars in credits if you are willing to spend the money and that should be enough to cover everyone. This project could also be used to teach js in a fun and interactive way.