How to connect ChatGPT with NodeJS
The application of?OpenAI?is?ChatGPT. You can ask to it whatever you wish. Of course, it can’t answer all questions and has no idea about the future just like?Google. But it can write poems, and offer some options depending on your questions.
In this article, I will cover how to create an application by using?ChatGPT APIs.
I will create a server using?NodeJS. And I will use?GraphQL?and?TypeScript?instead of Restful API and plain JavaScript. And my IDE will be?VSCode.
And I will need a secret API key to the connection.
I type the code below on the terminal to create the?package.json?file.
npm init
I install the packages, that I need to create?GraphQL.
npm install apollo-server graphql
I install the packages, that I need for?TypeScript:
npm install ts-node typescript
And I type the code that creates the?tsconfig.json?file
npx tsc -init
And the?openAI?package and two tools:
npm install openai nodemon dotenv
And now?dependencies?in the?package.json?folder need to seem like that:
领英推荐
And I add the?.env?and?index.ts?files:
And I add the codes below to the?index.ts?file:
import { ApolloServer } from "apollo-server"
import { Configuration, OpenAIApi } from "openai";
import dotenv from "dotenv";
dotenv.config();
const typeDefs = `
type Query{
ask_AQuestion(question:String):String
}
`;
const resolvers = {
Query: {
ask_AQuestion: async (_: any, args: any, context: any) => {
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const completion = openai.createCompletion({
model: "text-davinci-003",
prompt: args.question,
max_tokens: 1000,
});
let theAnswer;
await completion.then(async (r) => {
theAnswer = await r.data.choices[0].text;
console.info(r.data.choices[0].text);
});
return theAnswer;
},
},
};
const PORT = process.env.PORT || 5000;
const server = new ApolloServer({
typeDefs,
resolvers,
csrfPrevention: true,
cache: "bounded",
context: ({ req }: { req: any }) => {
const token = req.headers.authorization || "";
//console.log("authorization: " + token)
return { token };
},
});
server.listen({ port: PORT }).then(() => {
console.log(`?? Server ready at https://localhost:${PORT}`);
});;
You see in the file the valuable?OPENAI_API_KEY.?You can get it on the?OpenAI?website. First, you should create an account on the website and go to the “View API keys” page. And you can create here API keys.
Finally, if you type on the terminal
npm run start
you can see this page:
But please be sure that you add the node below in the file?package.json.
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1",
“start”: “nodemon src/index.ts”
}
And on the?Sandbox?page, you can ask ChatGPT any question you want!