💬

Integrating ChatGPT with React

Sep 23, 2024

OpenAI API Integration Tutorial

Introduction

  • Objective: Integrate ChatGPT into a React application using OpenAI's API.
  • Use Express as a dedicated server in Node.js.
  • Prerequisite: Node.js must be installed.

Application Overview

  • Application behaves like ChatGPT.
  • Example Queries:
    • What is React?
      • Response: "React is a JavaScript library for building user interfaces."
    • What is JavaScript?
      • Response: "JavaScript is a scripting language used to create and control dynamic website content."

Setting Up the Project

  1. Create a React Application

    • Command: mpx create-react-app chat-gpt-app
    • This creates a new folder and initializes a React app.
  2. OpenAI Account

    • Sign up at OpenAI.
    • Obtain your API key (do not share this key).
    • Ideally, store the API key in an .env file for security.
  3. Starting the Application

    • Change directory: cd chat-gpt-app
    • Start application: npm start
    • Set it to run on a specific port (e.g., 3002).

Creating the Server

Server Setup

  • Create server.js in the root of the project.
  • Install required packages:
    • Express: For creating Node.js servers.
    • CORS: Middleware for handling cross-origin requests.
    • Body Parser: Parses incoming request bodies.
    • OpenAI: Library for accessing OpenAI's API.
    • Axios: For making HTTP requests.
npm install express cors body-parser openai axios

Code for server.js

  1. Require Modules const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const OpenAI = require('openai'); const axios = require('axios');
  2. Configure OpenAI
    • Create a configuration object using your API key.
    • Example:
    const config = new OpenAI.Configuration({ apiKey: 'YOUR_API_KEY' });
  3. Create Express App const app = express(); app.use(cors()); app.use(bodyParser.json());
  4. Define Endpoint
    • Create a POST endpoint at /chat.
    • Use OpenAI to generate responses.
    • Example:
    app.post('/chat', async (req, res) => { const { prompt } = req.body; const completion = await openai.createCompletion({ model: "text-davinci-003", prompt }); res.send(completion.data.choices[0].text); });
  5. Start the Server const PORT = 8020; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Frontend Development

Setting Up the React Component

  1. Delete Existing Code in App.js and create a new component ChatGPTComponent.jsx.
  2. Import React and Required Hooks import React, { useState } from 'react'; import Axios from 'axios';
  3. Create State Variables for prompt and response: const [prompt, setPrompt] = useState(''); const [response, setResponse] = useState('');
  4. Handle Form Submission: Use Axios to make POST requests to the server.
    • Example:
    const handleSubmit = async (event) => { event.preventDefault(); const res = await Axios.post('http://localhost:8020/chat', { prompt }); setResponse(res.data); };
  5. Render Input Form: Create input fields and display response. <form onSubmit={handleSubmit}> <input type='text' value={prompt} onChange={(e) => setPrompt(e.target.value)} /> <button type='submit'>Ask</button> </form> <p>{response || 'Ask me anything!'}</p>

Conclusion

  • Run the application and test various questions using the ChatGPT integration.
  • Encourage viewers to subscribe for more tutorials.