0%
User Interface for ChatGPT: Building an Interactive Chat

User Interface

Building an interactive chat

10-15 min

User Interface for ChatGPT: Building an Interactive Chat

Introduction

In this module, we will build a modern, responsive user interface to interact with the ChatGPT API. We will use React to build our interface, but the concepts can be adapted to other frameworks.

Project Setup

Installing Dependencies

npm create vite@latest chatgpt-ui -- --template react
cd chatgpt-ui
npm install openai axios @chakra-ui/react @emotion/react @emotion/styled framer-motion

Project Structure

chatgpt-ui/
├── src/
│   ├── components/
│   │   ├── ChatWindow.jsx
│   │   ├── MessageInput.jsx
│   │   └── Message.jsx
│   ├── hooks/
│   │   └── useChatGPT.js
│   ├── App.jsx
│   └── main.jsx
└── .env

Building the Components

1. The useChatGPT Hook

// src/hooks/useChatGPT.js
import { useState } from 'react';
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: import.meta.env.VITE_OPENAI_API_KEY
});

export function useChatGPT() {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const sendMessage = async (content) => {
    try {
      setIsLoading(true);
      
      // Add the user's message
      const userMessage = { role: 'user', content };
      setMessages(prev => [...prev, userMessage]);

      // Call the ChatGPT API
      const completion = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [
          { role: "system", content: "Vous êtes un assistant utile." },
          ...messages,
          userMessage
        ],
      });

      // Add the assistant's response
      const assistantMessage = completion.choices[0].message;
      setMessages(prev => [...prev, assistantMessage]);

      return assistantMessage;
    } catch (error) {
      console.error('Erreur lors de l\'envoi du message:', error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  return {
    messages,
    isLoading,
    sendMessage
  };
}

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!