Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
How to integrate ChatGPT-3.5 Turbo into Node.js
Ngày đăng: 10/01/2024

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.


Contents

  1. What is ChatGPT-3.5 Turbo?
  2. Create your first ChatGPT application
  3. Setup ChatGPT-3.5 Turbo in Node.js
  4. Creating a ReactJS page
  5. Demo
  6. Get conversation via API
  7. Show the result to the UI
  8. Conclusion


What is ChatGPT-3.5?

  • ChatGPT-3.5 Turbo is a chatbot, developed by OpenAI.
  • ChatGPT is also a natural language processing (NLP) tool, that allows you to have human-like conversations.
  • The language model can answer questions and assist you with tasks, such as composing emails, essays, and code.


Create your first ChatGPT application


Setup ChatGPT-3.5 Turbo in Node.js


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
  • Enter the link on the web browser
  • Select API tab





  • Select API Keys on the left nav





  • Press Create new secret key button





  • Input your key name on the modal





  • Press Create secret key button
  • Past API Key into the 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"
}


Creating a ReactJS page


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;


Demo


Call API




React Page




Conclusion

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!!!!

Đề xuất

Create S3 Bucket with AWS CDK
admin09/06/2023

Create S3 Bucket with AWS CDK
In this article, I introduce Amazon CDK and how to write AWS infrastructure-as-code using TypeScript. We will do it step by step.
How to integrate ChatGPT-3.5 Turbo into Node.js
admin10/01/2024

How to integrate ChatGPT-3.5 Turbo into Node.js
Step-by-Step Guide to Incorporating ChatGPT-3.5 Turbo into Node.js for Basic ReactJS Applications
ĐINH THÀNH CÔNG - Software Developer
admin12/01/2024

ĐINH THÀNH CÔNG - Software Developer
Cong Dinh - Software Developer - My personal website, where I write blogs on a variety of topics and where I have some experiments with new technologies.
Mới nhất

Next.js 14 App Router Localization with next-intl
admin07/07/2024

Next.js 14 App Router Localization with next-intl
In this article, I will illustrate how to implement next-intl localization in a Next.js 14 application
Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
admin17/06/2023

Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
You are a beginner with Ghost CMS, Bitanami, AWS Lightsail and don't know much about the documentation yet. So, in this article, I introduce step by step to upgrade Ghost CMS to the latest version.
Part 4: Creating Static Home Page on Ghost CMS
admin17/06/2023

Part 4: Creating Static Home Page on Ghost CMS
I believe that many of you are asking the question: How to fix the home page of Ghost CMS as desired? and are struggling to find many different sources of documentation.
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About