Set Up Your OpenAI Account
- Create an account on the OpenAI platform if you don't have one already.
- Generate your API key. This will be necessary for making authorized requests to OpenAI services.
Install the Heroku CLI
Create a New Heroku App
Set Up Your Node.js Application
- Ensure you have Node.js and npm installed on your local machine.
- Initialize a new Node.js application and install necessary dependencies:
```shell
npm init -y
npm install express openai
```
Here, we’ll use Express for our server and OpenAI for interacting with OpenAI's API.
Create the Server Application
- Create a new file named `server.js` in the root of your project directory.
- Inside `server.js`, set up a basic Express server and integrate the OpenAI API using your API key:
```javascript
const express = require('express');
const { OpenAI } = require('openai');
const app = express();
const openai = new OpenAI('');
app.use(express.json());
app.post('/ask', async (req, res) => {
const { query } = req.body;
try {
const response = await openai.Completions.create({
model: "text-davinci-003",
prompt: query,
max_tokens: 100,
});
res.json(response.data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(Server running on port ${PORT}
));
```
Replace '<Your-API-Key>'
with your actual OpenAI API key.
Configure Git for Deployment
Deploy to Heroku
Manage Environment Variables
Test Your Integration
- Use a tool like Postman to send a POST request to https://.herokuapp.com/ask with JSON payload `{"query": "Hello World!"}` to test if it's working.