Last active
September 8, 2021 11:05
-
-
Save bramses/2b1a72c4269b8a892a7ebf7318d1b363 to your computer and use it in GitHub Desktop.
Run OpenAI API in NodeJS Express Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import openai | |
| import os | |
| from dotenv import load_dotenv | |
| import sys | |
| load_dotenv() | |
| TOKEN_RESPONSE_LENGTH = 20 | |
| TEMPERATURE = 0.75 | |
| STOP = "\n" | |
| ENGINE = "davinci" | |
| def loadEnv(): | |
| return os.getenv("OPENAI_API_KEY") | |
| def generate_response(prompt, max_tokens, temp, stop, engine): | |
| return openai.Completion.create(engine=engine, prompt=prompt, max_tokens=max_tokens, temperature=temp, stop=stop) | |
| def run(prompt): | |
| openai.api_key = loadEnv() | |
| res = generate_response(prompt, TOKEN_RESPONSE_LENGTH, TEMPERATURE, STOP, ENGINE) | |
| return res | |
| if __name__ == '__main__': | |
| print(run(sys.argv[1])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // calling fetch() in your React frontend | |
| const res = await fetch('http://localhost:5000/get-message', { | |
| method: 'POST', | |
| mode: 'cors', | |
| credentials: 'same-origin', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| body: JSON.stringify({ | |
| message: generatePrompt() | |
| }) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const app = express(); | |
| const spawn = require("child_process").spawn; | |
| const cors = require('cors'); | |
| const bodyParser = require('body-parser'); | |
| app.use( bodyParser.json() ); // to support JSON-encoded bodies | |
| app.use(bodyParser.urlencoded({ // to support URL-encoded bodies | |
| extended: true | |
| })); | |
| app.use(cors()); | |
| app.post('/get-message', (req, res) => { | |
| console.log(req.body.message) | |
| const pythonProcess = spawn("python", ["./api.py", req.body.message ]); | |
| pythonProcess.stdout.on("data", function (data) { | |
| res.setHeader('Content-Type', 'application/json'); | |
| res.end(data.toString()) | |
| }); | |
| }) | |
| app.listen(5000, function() { | |
| console.log('server running on port 5000'); | |
| }) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm init -yto start a new servernpm i express cors body-parserto install dependenciesnpm startto run