Hooks
useChatGPT

useChatGPT Hook

Introduction

The useChatGPT custom hook provides a convenient way to interact with the OpenAI ChatGPT API within React applications. By utilizing this hook, developers can easily fetch responses from the ChatGPT model based on user-provided messages.

Installation

To use the useChatGPT hook in your React application, you need to follow these installation steps:

  1. Ensure that you have React installed in your project.

  2. Install the necessary dependencies:

npm install axios

Usage

Once installed, you can use the useChatGPT hook within your React components as follows:

import React, { useState } from 'react';
import {useChatGPT} from 'use-ai-hooks'; // Import the custom hook
 
const ChatGPTComponent = () => {
  const [messages, setMessages] = useState([{ role: 'user', content: '' }]);
  const [model, setModel] = useState('gpt-3.5-turbo');
  const apiKey = 'YOUR_API_KEY'; // Your OpenAI API key
 
  const { response, error, loading, fetchChatGPTResponse } = useChatGPT(apiKey);
 
  const handleSendMessage = async () => {
    if (messages[messages.length - 1].content !== '') {
      const newMessages = [...messages, { role: 'user', content: '' }];
      setMessages(newMessages);
      await fetchChatGPTResponse({ model, messages: newMessages });
    }
  };
 
  const handleInputChange = (index, value) => {
    const newMessages = [...messages];
    newMessages[index].content = value;
    setMessages(newMessages);
  };
 
  return (
    <div>
      <h1>Chat with GPT-3</h1>
      <div>
        {messages.map((message, index) => (
          <div key={index}>
            <input
              type="text"
              value={message.content}
              onChange={(e) => handleInputChange(index, e.target.value)}
              placeholder={`Message ${index + 1}`}
            />
          </div>
        ))}
      </div>
      <button onClick={handleSendMessage} disabled={loading}>
        Send
      </button>
 
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {response && <div>
        <h2>Response</h2>
        <p>{response}</p>
      </div>}
    </div>
  );
};
 
export default ChatGPTComponent;
 

API Reference

Parameters

  • apiKey (string): The API key required to authenticate requests to the OpenAI ChatGPT API.

Returns

An object with the following properties:

  • response (string | null): The response text obtained from the ChatGPT model.
  • error (object | null): An object containing information about any errors that occurred during the API request.
    • message (string): A description of the error that occurred.
  • loading (boolean): A boolean indicating whether the API request is currently in progress.
  • fetchChatGPTResponse(options: ChatGPTOptions): A function to fetch a response from the ChatGPT model based on the provided options.

Hook

import { useState } from "react";
import axios from "axios";
 
interface ChatGPTOptions {
  model?:
    | "gpt-3.5-turbo-0125"
    | "gpt-3.5-turbo"
    | "gpt-3.5-turbo-1106"
    | "gpt-3.5-turbo-instruct"
    | "pt-3.5-turbo-16k"
    | "gpt-3.5-turbo-0613"
    | "gpt-3.5-turbo-16k-0613";
  messages: { role: string; content: string }[];
}
 
interface ApiError {
  message: string;
}
 
const useChatGPT = (apiKey: string) => {
  const [response, setResponse] = useState<string | null>(null);
  const [error, setError] = useState<ApiError | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
 
  const fetchChatGPTResponse = async (options: ChatGPTOptions) => {
    setLoading(true);
    setError(null);
 
    try {
      const result = await axios.post(
        "https://api.openai.com/v1/chat/completions",
        {
          model: options.model ?? "gpt-3.5-turbo",
          messages: options.messages,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`,
          },
        }
      );
 
      const responseText = result.data.choices[0]?.message?.content;
      setResponse(responseText || null);
      return responseText;
    } catch (err) {
      if (axios.isAxiosError(err)) {
        setError({ message: err.message });
        
      } else {
        setError({ message: "An unexpected error occurred" });
      }
      return err;
    } finally {
      setLoading(false);
    }
  };
 
  return { response, error, loading, fetchChatGPTResponse };
};
 
export default useChatGPT;