Using OpenAI API with Node.js
Introduction
This tutorial demonstrates how to integrate and use the OpenAI API with Node.js to leverage advanced AI capabilities in your applications.
1. Setting Up Your OpenAI API Key
Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.
2. Making API Requests
To make requests to the OpenAI API using Node.js, you'll use the `axios` library for HTTP requests.
Text Completion
Here’s an example of making a request for text completion:
const axios = require('axios'); const apiKey = 'YOUR_API_KEY_HERE'; const url = 'https://api.openai.com/v1/completions'; axios.post(url, { prompt: 'Translate English to French: Hello, how are you?', max_tokens: 50 }, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }) .then(response => { console.log(response.data.choices[0].text.trim()); }) .catch(error => { console.error('Error:', error); });
Output: Bonjour, comment vas-tu ?
This Node.js script sends a POST request to the OpenAI API for text completion and logs the API response.
Code Generation
Here’s an example of making a request for code generation:
const axios = require('axios'); const apiKey = 'YOUR_API_KEY_HERE'; const url = 'https://api.openai.com/v1/engines/davinci-codex/completions'; axios.post(url, { prompt: 'Generate Python code to sort an array using bubble sort', max_tokens: 150, stop: ['\n'] }, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }) .then(response => { console.log(response.data.choices[0].text.trim()); }) .catch(error => { console.error('Error:', error); });
Output:
def sort_list(list): list.sort() return list my_list = [3, 1, 4, 2] print(sort_list(my_list))
This Node.js script sends a POST request to the OpenAI Codex engine for code generation and logs the generated code.
3. Handling Responses
Once you receive a response from the API, you can handle it in your Node.js code.
Text Completion
Here’s how you might handle the completion response:
// Assuming `response` contains the API response object console.log(response.data.choices[0].text.trim());
In this example, `response` contains the JSON response from the OpenAI API.
Code Generation
Here’s how you might handle the code generation response:
// Assuming `response` contains the API response object console.log(response.data.choices[0].text.trim());
In this example, `response` contains the JSON response from the OpenAI API with the generated code.
Conclusion
Integrating the OpenAI API with Node.js allows you to enhance your applications with powerful AI capabilities. Explore more API endpoints and functionalities to innovate further.