This article illustrates how to integrate ChatGPT-3.5 Turbo into Node.js and shows the result on ReactJS. We will show a very basic setup.
1. Create a new Node.js Application:
Run the command below to create a new node.js application
yarn init
2. Install packages:
OpenAI package
yarn add openai
3. Setup OpenAI:
Add apiKey into .env file
Use the completion function to get response
async generateSubTitle(title: string): Promise<string> { const response = await this._openAiClient.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [ { role: 'user', content: title, }, ], max_tokens: 100, }); return response.choices[0].message.content ?? ''; }
Add new route to generate sub title base on article's title
POST /api/v1/articles/sub-title-generator Body: { title: "How to use GPT-3.5 Turbo Instruct Node.js" }
import React, { useCallback, useState } from 'react'; import { useRouter } from 'next/router'; import { IconButton } from '@mui/material'; import AutoFixNormal from '@mui/icons-material/AutoFixNormal'; import axios from 'axios'; function PostPage() { const router = useRouter(); const [titleValue, setTitleValue] = useState(''); const [generateDescriptionProcessing, setGenerateDescriptionProcessing] = useState(false); const [generateSubTitleValue, setGenerateSubTitleValue] = useState(''); const generateDescription = useCallback(async () => { try { const common = `a new sub title base on title: ${titleValue} ${ router.locale === 'en' ? '' : 'using the Vietnameses' }`; setGenerateDescriptionProcessing(true); const res = await axios.post<IHttpResponse<string>>(`/articles/sub-title-generator`, { title: common, }); setGenerateSubTitleValue(res.data.data.record); } catch (error) { } finally { setGenerateDescriptionProcessing(false); } }, [router.locale, titleValue]); return ( <> <input type="text" value={titleValue} onChange={(e) => setTitleValue(e.target.value)} placeholder="Enter post title" /> <textarea value={generateSubTitleValue} readOnly /> <IconButton className="bg-blue-500 text-white ml-3 shadow" disabled={!titleValue || generateDescriptionProcessing} onClick={generateDescription} > <AutoFixNormal /> </IconButton> </> ); } export default PostPage;
OpenAI provides an API to integrate into your application, the API is easy to use and config. Furthermore, OpenAI has provided a powerful chatbot to answer the questions more like humans.
The API can also be used for commercial purposes for building scalable applications.
Good luck to you, hope this post is of value to you!!!!