Cookie Consent by Free Privacy Policy Generator
What's new Search

How to connect to GPT-4 API with Node.js using PowerShell



First, install the axios library using PowerShell, this assumes that you have already installed Node.js
Code:
npm install axios


1, Create a new folder, name it whatever you like.
2, Create a new js file, I have named it index.js
3, Paste the following code in to the index.js file
4, Replace the API key with your own API key
5, Save the file
Code:
const axios = require("axios");

// Replace with your real API key
const apiKey = "sk-";

const openai = axios.create({
  baseURL: "https://api.openai.com/v1",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${apiKey}`,
  },
});

async function generateChatCompletion(messages, options = {}) {
  try {
    const response = await openai.post("/chat/completions", {
      model: options.model || "gpt-4",
      messages,
      ...options,
    });

    return response.data.choices;
  } catch (error) {
    console.error("An error occurred while creating the chat completion: ", error);
  }
}

async function executeMain() {
  const messages = [
    { role: "system", content: "You are a helpful SEO assistant." },
    { role: "user", content: "Tell me about Core Web Vitals." },
  ];

  const options = {
    temperature: 0.8,
    max_tokens: 4000,
  };

  const choices = await generateChatCompletion(messages, options);

  console.log("User: ", messages[messages.length - 1].content);
  console.log("Assistant: ", choices[0].message.content);
}

executeMain();

6, Open PowerShell
7, Change directory to your newly created folder with the index.js. Example cd C:\Users\chris\test
8, Execute your index.js script - node index.js

If all went to plan you should have your prompt response similar to the image posted above. If it did not work, try following all steps again. Making sure that you have Node.js and Axios installed.

Thanks for reading.
 
Last edited:
C
Written by

Chris

Administrator
Staff member
Back
Top