4-Generate Chat Completions with AI in Node.js Using the OpenAI SDK & GPT
Generate Chat Completions with AI in Node.js Using the OpenAI SDK
In the rapidly evolving world of artificial intelligence, generating chat completions has become a significant application. This tutorial will guide you through the process of setting up a Node.js application that utilizes the OpenAI SDK to generate chat completions using the GPT model. Let’s get started!
Prerequisites
Before we dive into the code, ensure you have the following:
- Node.js installed on your machine. You can download and install it from Node.js official website.
- An OpenAI API key. Sign up at OpenAI's website and obtain your API key from the API section.
Setting Up Your Project
Step 1: Create a New Node.js Project
First, create a new directory for your project and navigate to it in your terminal.
mkdir chat-completion-app
cd chat-completion-app
Then, initialize a new Node.js project:
npm init -y
Step 2: Install OpenAI SDK
Next, you need to install the OpenAI SDK. Run the following command in your project directory:
npm install openai
Writing the Code
Now that we have the project set up and the SDK installed, let’s write the code to generate chat completions.
Step 3: Create a JavaScript File
Create a new file named chat.js:
touch chat.js
Step 4: Write the Chat Completion Logic
Open chat.js in your favorite text editor and add the following code:
// Import the OpenAI SDK
const { Configuration, OpenAIApi } = require("openai");
// Initialize OpenAI with your API key
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY, // Store your API key in an environment variable
});
const openai = new OpenAIApi(configuration);
// Function to generate chat completion
async function generateChatCompletion(prompt) {
try {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo", // Specify the model you want to use
messages: [{ role: "user", content: prompt }],
});
console.log("Chat Completion:", response.data.choices[0].message.content);
} catch (error) {
console.error("Error generating chat completion:", error);
}
}
// Example usage
const userPrompt = "Hello, how are you?";
generateChatCompletion(userPrompt);
Explanation of the Code
- Importing SDK: We import the necessary classes from the OpenAI SDK.
- Configuration: We create a new configuration instance using our OpenAI API key. It’s good practice to store sensitive information like your API key in environment variables.
- Chat Completion Function: The
generateChatCompletionfunction takes a user prompt as input and calls the OpenAI API to generate a chat completion. - Error Handling: Any errors during the API call will be caught and logged to the console.
- Example Usage: Finally, we call the function with a sample user prompt.
Step 5: Set Up Environment Variables
To use environment variables, you can create a .env file in your project directory:
touch .env
Add your OpenAI API key to the .env file:
OPENAI_API_KEY=your_openai_api_key_here
Make sure to replace your_openai_api_key_here with your actual API key.
To load the environment variables, you will need to install the dotenv package:
npm install dotenv
Then, modify your chat.js file to include the following line at the top:
require('dotenv').config();
Running the Application
With everything set up, you can now run your application. In your terminal, execute the following command:
node chat.js
If everything is working correctly, you should see a chat completion response printed in the console.
Conclusion
In this tutorial, we walked through the steps to generate chat completions using the OpenAI SDK in a Node.js application. You learned how to set up a project, write the necessary code, and handle API calls efficiently. With this foundational knowledge, you can explore further applications of AI in your projects. Happy coding!
Feel free to experiment with different prompts and see how the AI responds. The possibilities are endless!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment