Prerequisites
- Ensure you have a working installation of Visual Studio Code (VS Code) on your machine.
- Ensure you have a valid API key from OpenAI. You can generate or view your API keys in your OpenAI account dashboard.
- Ensure you have Node.js and npm installed, as they are required for extending VS Code with additional packages.
Install Required VS Code Extensions
- Open VS Code and navigate to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window.
- Search for and install the "REST Client" extension. This extension allows you to send HTTP requests and examine responses directly within VS Code.
Create a New Project Folder
- Open a new terminal in VS Code.
- Run the following commands to set up a new directory and initialize a Node.js project within it:
mkdir openai-integration
cd openai-integration
npm init -y
Install OpenAI Client Library
- Within the project folder, install the OpenAI Node.js client library:
npm install openai
Create an API Interaction Script
- Create a new file named
openai.js
within your project folder.
- Populate this file with a script to interact with the OpenAI API:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function fetchOpenAICompletion() {
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: "Hello, world!",
max_tokens: 50,
});
console.log(response.data.choices[0].text.trim());
} catch (error) {
console.error("Error fetching completion from OpenAI:", error);
}
}
fetchOpenAICompletion();
Set Up Environment Variables
- Create a file named
.env
in the root of your project folder.
- Add your OpenAI API key to this file:
OPENAI_API_KEY=your_api_key_here
Install dotenv Package
- Ensure your Node.js script can access environment variables by installing the
dotenv
package:
npm install dotenv
Modify Your Script to Use dotenv
- Make sure to import and configure
dotenv
at the top of your openai.js
file:
require('dotenv').config();
Run Your Script
- Execute your script from the terminal to test the OpenAI integration:
node openai.js
View API Response in VS Code
- Check the terminal output in VS Code for your OpenAI API response, ensuring everything is functioning as expected.
Optional: Using REST Client in VS Code
- Create a new file named
request.http
to use the REST Client extension.
- Add the following HTTP request format to the file:
POST https://api.openai.com/v1/engines/text-davinci-003/completions
Authorization: Bearer your_api_key_here
Content-Type: application/json
{
"prompt": "Hello, world!",
"max_tokens": 50
}
- Click "Send Request" above the request to get a response from OpenAI directly in VS Code.
Documentation and Further Learning
- Familiarize yourself with the OpenAI API documentation to explore additional capabilities and parameters.
open https://beta.openai.com/docs/