Chat GPT-3.5-turbo Client with React Native

ยท

5 min read

In this article, you gonna learn about how to integrate the Chat GPT API into your react native app and use it as a Chat GPT client. We are using gpt-3.5-turbo client.

STEPS:

  1. Sing up for Open AI API

  2. Create a new RN app

  3. Installing the necessary dependencies

  4. Setup the chat interface

  5. Connect to GPT-3.5-turbo API

  6. Update the chat interface with the response

  7. Test the chat interface

1. Sign up for Open AI API

You need an API key to access the Chat GPT API.
You can signup here
After successful signup navigate to your Account API keys.
You can check the below image to find the section or click here

Now click on create a new secret key. Copy it and keep it somewhere safe.
We completed step 1.

2. Create a new RN app

npx react-native init <projectname>

We completed step 2.

3. Installing the necessary dependencies

  • axios - To make HTTP calls to gpt-3.5-turbo API

  • react-native-gifted-chat - To create a chat interface

  • react-native-dotenv - To store CHAT GPT API KEY

yarn add axios react-native-gifted-chat
yarn add -D react-native-dotenv

We completed step 3.

4. Setup the chat interface

We are using react-native-gifted-chat package to create a chat interface. You can use the below code to create a simple chat interface.

Create a new JS file called ChatScreen.js

import React, { useState, useEffect } from 'react'; 
import { GiftedChat } from 'react-native-gifted-chat'; 

const ChatScreen = () => { 
const [messages, setMessages] = useState([]); 

const onSend = (newMessages = []) => { 
setMessages((prevMessages) => GiftedChat.append(prevMessages, newMessages)); 
}; 

return <GiftedChat messages={messages} onSend={onSend} />; }; 

export default ChatScreen;

From the above code

  • messages - All chat activity is stored in the form of a messages array

  • setMessages - To update the messages state

  • onSend callback accepts the newMessages array which has values in the form of below

  •     [
          {
            "text": "Hey",
            "user": {
              "_id": 1,
              "name": "Developer",
              "avatar": 1
            },
            "createdAt": "2023-03-26T22:01:38.086Z",
            "_id": "587163d0-4335-4cab-830b-224db9e9413b"
          }
        ]
    
  • onSend callback is called when the user wanna ask any question to gpt-3.5-turbo client and press send button from the chat interface

  • We completed step 4.

5. Connect to GPT-3.5-turbo API

We are using axios package to make a post request to the GPT-3 API with the user's message.
Let's add the API configuration to our ChatScreen file.
Don't forget to import axios in ChatScreen.js file
Don't forget to add your key to .env file and import it in ChatScreen.js file

import React, {useState} from 'react';
import {GiftedChat} from 'react-native-gifted-chat';
import {CHAT_GPT_API_KEY} from '@env';
import axios from 'axios';

const ChatScreen = () => {
  const [messages, setMessages] = useState([]);

  const sendMessage = async (message: string) => {
    try {
      const response = await axios.post(
        'https://api.openai.com/v1/chat/completions',
        {
          messages: [
            {
              role: 'user',
              content: message,
            },
          ],
          model: 'gpt-3.5-turbo',
        },
        {
          headers: {
            Authorization: `Bearer ${CHAT_GPT_API_KEY}`,
            'Content-Type': 'application/json',
          },
        },
      );

      return response.data.choices[0].message.content;
    } catch (err) {
      console.log(err, 'api call error');
    }
  };

  const onSend = (newMessages = []) => { 
    setMessages((prevMessages) => GiftedChat.append(prevMessages,                   newMessages)); 
  }; 

  return <GiftedChat messages={messages} onSend={onSend} />;
};

export default ChatScreen;

From the above code

  • The post request URL is: api.openai.com/v1/chat/completions

  • The model we are using is: gpt-3.5-turbo

  • Remember that you copied and saved the API key from Open AI, you need to add that key in the header of your post request as an authorization parameter

  • Content-type: application/json

  • data accepts two mandatory fields

  • messages array accepts an array of objects as input

  • Each object inside message array must have role and content key, value pairs

  • model is another mandatory param that should say which gpt model you are accessing, In our case we are using gpt-3.5-turbo model

We completed step 5.

6. Update the chat interface with the response

Once you receive a response from the gpt-3.5-turbo API, update the chat interface with the message by updating the onSend function in the chat interface.

import React, {useState} from 'react';
import {GiftedChat} from 'react-native-gifted-chat';
import {CHAT_GPT_API_KEY} from '@env';
import axios from 'axios';

const ChatScreen = () => {
  const [messages, setMessages] = useState([]);

  const sendMessage = async (message: string) => {
    try {
      const response = await axios.post(
        'https://api.openai.com/v1/chat/completions',
        {
          messages: [
            {
              role: 'user',
              content: message,
            },
          ],
          model: 'gpt-3.5-turbo',
        },
        {
          headers: {
            Authorization: `Bearer ${CHAT_GPT_API_KEY}`,
            'Content-Type': 'application/json',
          },
        },
      );

      return response.data.choices[0].message.content;
    } catch (err) {
      console.log(err, 'api call error');
    }
  };

  const onSend = async (newMessages = []) => {
    setMessages(prev => GiftedChat.append(prev, newMessages));

    const response = await sendMessage(newMessages[0].text);
    const chatMessage = [
      {
        _id: Math.random().toString(36).substring(7),
        text: response,
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'GPT-3.5-turbo',
          avatar: require('../assets/chatgptlogo.png'),
        },
      },
    ];

    setMessages(prev => GiftedChat.append(prev, chatMessage));
  };

  return <GiftedChat messages={messages} onSend={onSend} />;
};

export default ChatScreen;

We completed step 6.

7. Test the chat interface

Start your react native app and test the chat interface. Now you should be able to send messages to gpt-3.5-turbo API and receive responses.

Adding some styles to the text input and setting the user data

the final code of the simple chat screen may look like below.

import React, {useState} from 'react';
import {GiftedChat, InputToolbar} from 'react-native-gifted-chat';
import {CHAT_GPT_API_KEY} from '@env';
import axios from 'axios';
import {StyleSheet} from 'react-native';

const ChatScreen = () => {
  const [messages, setMessages] = useState([]);

  const sendMessage = async (message: string) => {
    try {
      const response = await axios.post(
        'https://api.openai.com/v1/chat/completions',
        {
          messages: [
            {
              role: 'user',
              content: message,
            },
          ],
          model: 'gpt-3.5-turbo',
        },
        {
          headers: {
            Authorization: `Bearer ${CHAT_GPT_API_KEY}`,
            'Content-Type': 'application/json',
          },
        },
      );

      return response.data.choices[0].message.content;
    } catch (err) {
      console.log(err, 'api call error');
    }
  };

  const onSend = async (newMessages = []) => {

    setMessages(prev => GiftedChat.append(prev, newMessages));

    const response = await sendMessage(newMessages[0].text);
    const chatMessage = [
      {
        _id: Math.random().toString(36).substring(7),
        text: response,
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'GPT-3.5-turbo',
          avatar: require('../assets/chatgptlogo.png'),
        },
      },
    ];

    setMessages(prev => GiftedChat.append(prev, chatMessage));
  };

  const user = {
    _id: 1,
    name: 'Developer',
    avatar: require('../assets/profile.jpeg'),
  };

  const renderInputToolbar = props => {
    return <InputToolbar {...props} containerStyle={styles.input} />;
  };

  return (
    <GiftedChat
      messages={messages}
      onSend={onSend}
      user={user}
      placeholder={'whats on your mind?'}
      showUserAvatar={true}
      showAvatarForEveryMessage={true}
      renderInputToolbar={renderInputToolbar}
      messagesContainerStyle={styles.messageContainer}
    />
  );
};

export default ChatScreen;

const styles = StyleSheet.create({
  messageContainer: {
    paddingBottom: 16,
  },
  input: {
    borderColor: 'transparent',
    borderWidth: 0,
    borderRadius: 4,
    marginBottom: 16,
  },
});

Bazinga! ๐Ÿ––๐Ÿป Now you have a completely working gpt-3.5-turbo client in react native app.

Happy hacking! ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป