==

Q-Consultation for every industry

Securely hold virtual meetings and video conferences

Learn More>

Want to learn more about our products and services?

Speak to us now

Integrating AI Features into your React App made Easy

Artem Koltunov
5 Dec 2023
React App with AI features

Integrating artificial intelligence (AI) into personal applications is now the number one task for programmers and developers. To simplify this challenge, QuickBlox has created an AI enhanced Chat React UI Kit. Pre-enabled with a series of AI Extensions (AI Answer Assist, AI Translate, and AI Rephrase) our UI Kit makes it easy to build a cutting edge chat application in no time at all.

But what if you want to build an application using our AI Extensions, but independently from our React UI Kit? No problem! We have now created a series of individual AI libraries that you can use for your projects. Read on to discover just how easy it is to implement these libraries into your application, allowing you to create apps that are truly stunning and appealing to diverse audiences.

Ready to get started?

What are the React AI Extension Libraries?

Each of our React AI libraries serves as a set of tools to enhance React chat applications. Let’s explore the fundamental functions of each library.

For a more detailed exploration of the functionality of these features, check out our earlier blogs:
Supercharge Your Web Chat Apps with ChatGPT AI Answer Assist
Enabling Multilingual Communication for your Chat Apps with AI Translate
From Formal to Friendly: Unveiling AI Rephrase for your Chat Apps

The qb-ai-answer-assistant Library

AI Answer Assist allows users to generate quick answer responses to chat messages. This library provides the capability to generate responses based on the conversation context using ChatGPT.

Usage:

import { ChatMessage } from 'qb-ai-core';
import { AIAnswerAssistantSettings, QBAIAnswerAssistant } from 'qb-ai-answer-assistant';

let prompt = "YOUR_REQUEST_FOR_AI_ANSWER_ASSISTANT";

let messages = [
  {role: Role.other, content: "Hello, Bob!"},
  {role: Role.me, content: "Hello, Jim!"},
  {role: Role.me, content: prompt},
];

const settings: AIAnswerAssistantSettings = QBAIAnswerAssistant.createDefaultAIAnswerAssistantSettings();
settings.apiKey = 'YOUR_OPEN_AI_API_KEY';

return QBAIAnswerAssistant.createAnswer(prompt, messages, settings);

The qb-ai-translate Library

AI Translate enables users to translate messages into a different language translation during a chat. The library supports various languages.

Usage:

import { ChatMessage } from 'qb-ai-core';
import { AITranslateSettings, QBAITranslate } from 'qb-ai-translate';

let prompt = "YOUR_TEXT_FOR_TRANSLATION";

let messages = [
  {role: Role.other, content: "Hello, Bob!"},
  {role: Role.me, content: "Hello, Jim!"},
  {role: Role.me, content: prompt},
];

const settings: AITranslateSettings = QBAITranslate.createDefaultAITranslateSettings();
settings.apiKey = 'YOUR_OPEN_AI_API_KEY';
settings.language = 'YOUR_LANGUAGE';  // in BCP47 format

return QBAITranslate.translate(prompt, messages, settings);

The qb-ai-rephrase Library

AI Rephrase allows users to find alternative ways to express their message by selecting a particular style (e.g. formal, friendly, poetic etc)

Usage:

import { ChatMessage } from 'qb-ai-core';
import { AIRephraseSettings, QBAIRephrase } from 'qb-ai-rephrase';

let prompt = "YOUR_TEXT_FOR_REPHRASING";

let messages = [
  {role: Role.other, content: "Hello, Bob!"},
  {role: Role.me, content: "Hello, Jim!"},
  {role: Role.me, content: prompt},
];

const settings: AIRephraseSettings = QBAIRephrase.createDefaultAIRephraseSettings();
settings.apiKey = 'YOUR_OPEN_AI_API_KEY';
settings.tone = { name : 'YOUR_TONE_NAME', description: 'TONE_DESCRIPTION', iconEmoji: 'YOUR_EMOJI' };

return QBAIRephrase.rephrase(prompt, messages, settings);

These libraries provide powerful tools to enhance your chat application functionality, allowing you to generate intelligent responses, translate messages, and apply styles to messages, making your dialogues more engaging and efficient.

Building a Simple Chat Application with AI Extensions

In the following section we will guide you through the process of creating a simple chat application in React, in which the user can interact with ChatGPT using our libraries. In this application, we will implement a unique communication experience. First, the user’s messages will be automatically translated into English (AI Translate), then re-written in a poetic form (AI Rephrase), and finally, the user will receive an AI-generated response to a message (AI Answer Assist). Let’s embark on this exciting journey into the world of creating interactive and intelligent chat applications!

Preparation:
Before we start to use the libraries to enhance your chat application, you’ll need a React project. If you don’t have one, follow the steps below:

Create a React Project:
Open your terminal or command prompt.
Enter the command: npx create-react-app my-chat-app --template typescript
Navigate into the created folder: cd my-chat-app

Install the Libraries:
To install the qb-ai-answer-assistant, qb-ai-rephrase, and qb-ai-translate libraries, use the following command:

npm install qb-ai-answer-assistant qb-ai-rephrase qb-ai-translate

Great! You now have the required development foundation, and the libraries are installed and ready to be used in your React project.

Implementing AI Translate

First, let’s incorporate the logic of our AI Translate library.

Step 1:

  • Open the App.tsx file, which is automatically generated and contains the markup and logic for our main (and only) application page. It should look like this:

    (In case your code is generated in a Javascript style, change it to our version, which uses a functional components approach)

import React, { useState } from 'react';

const App: React.FC = () => {
  return (
      
Hello, world!
); }; export default App;

Step 2: Let’s add the markup

  • place a component for message input
  • add a button to send it to ChatGPT using our library
  • create a list of messages – the history of our communication with ChatGPT
import React, { useState } from 'react';

interface Message {
  role: string;
  content: string;
}

const App: React.FC = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();

    if (inputValue.trim() === '') return;

    setMessages([...messages, { role: 'user', content: inputValue }]);
    setInputValue('');
  };

  return (
      
{messages.map((message, index) => (
{message.role === 'user' ? You: : ChatGPT:} {message.content}
))}
setInputValue(e.target.value)} />
); }; export default App;

Step 3: Let’s react to the fact that the user created a new message and it needs to be processed. Add a useEffect in which we will call our library as shown above.

import React, { useState, useEffect } from 'react';
import { AITranslateSettings, QBAITranslate } from 'qb-ai-translate';  // Import the necessary components

const App: React.FC = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');

  useEffect(() => {
    const sendToQBLibrary = async () => {
      if (inputValue.trim() === '') return;

      try {
        const aiTranslateSettings: AITranslateSettings =
            QBAITranslate.createDefaultAITranslateSettings();

        aiTranslateSettings.apiKey = 'sk-…k7qJz'; // your apiKey from the OpenAI admin panel
        aiTranslateSettings.language = 'Ukrainian';

        const result: string =  await QBAITranslate.translate(
            inputValue,
            messages,
            aiTranslateSettings,
        );
        const outputMessage = { role: 'assistant', content: result }
        setMessages([...messages, outputMessage]);
      } catch (error) {
        console.error('Error while executing the request:', error);
      }
    };

    // Call the function whenever messages change
    sendToQBLibrary();
    setInputValue('');
  }, [inputValue, messages]);

  // Rest of your code...
};

export default App;

This setup will enable your React application to interact with ChatGPT using the provided libraries.

Note: For the language name, you should use the BCP47 format accepted in the browser’s navigator property.

For example, here is how these formats look for English, Spanish, German, French, and Ukrainian languages:

{code: ‘en-US’, language: ‘English’},
{code: ‘de-DE’, language: ‘German’},
{code: ‘es-ES’, language: ‘Spanish’},
{code: ‘fr-FR’, language: ‘French’},
{code: ‘uk-UA’, language: ‘Ukrainian’}

You can read more about this format at the following links: MDN Web Docs – Navigator.language property and RFC 5646 – Tags for identifying languages

Adding AI Rephrase & AI Answer Assist

Step 4: Similar to working with AI Translate, let’s add the functionality for AI Rephrase and AI Answer Assistant.

useEffect(() => {
  const sendToQBLibrary = async () => {
    if (inputValue.trim() === '') return;

    try {
      const aiRephraseSettings: AIRephraseSettings = QBAIRephrase.createDefaultAIRephraseSettings();
      aiRephraseSettings.apiKey = 'sk…Hdqk7qJz';
      aiRephraseSettings.tone = { name: 'Poetic', description: '', iconEmoji: '' };

      const resultRephrase: string = await QBAIRephrase.rephrase(inputValue, messages, aiRephraseSettings);
      const outputRephraseMessage = { role: 'assistant', content: resultRephrase }
      setMessages([...messages, outputRephraseMessage]);

      const aiAnswerAssistantSettings: AIAnswerAssistantSettings = QBAIAnswerAssistant.createDefaultAIAnswerAssistantSettings();
      aiAnswerAssistantSettings.apiKey = 'sk-...Hdqk7qJz';

      const resultAssistant: string = await QBAIAnswerAssistant.createAnswer(inputValue, messages, aiAnswerAssistantSettings);
      const outputAssistantMessage = { role: 'assistant', content: resultAssistant }
      setMessages([...messages, outputAssistantMessage]);
    } catch (error) {
      console.error('Error while executing the request:', error);
    }
  };

  // Call the function whenever messages change
  sendToQBLibrary();
  setInputValue('');
}, [inputValue, messages]);

This setup will enable your React application to interact with ChatGPT using the provided libraries for translation, rephrasing, and generating responses.

A Note about AI Rephrase:
With AI Rephrase, you can specify the speech style as shown in our example, or you can add your description of this style. For instance, in the library, there is a method called QBAIRephrase.defaultTones(), which allows you get a list of default tones and lets you know the descriptions. And after that, you can edit the list and use your modified list instead. Here is a snippet from the Chat React UI Kit settings file to demonstrate the styles already available in our library:

//…
defaultTone: 'Professional',
Tones: [
  {
    name: 'Professional Tone',
    description:
      'This would edit messages to sound more formal, using technical vocabulary, clear sentence structures, and maintaining a respectful tone. It would avoid colloquial language and ensure appropriate salutations and sign-offs',
    iconEmoji: 'πŸ‘”',
  },
  {
    name: 'Friendly Tone',
    description:
      'This would adjust messages to reflect a casual, friendly tone. It would incorporate casual language, use emoticons, exclamation points, and other informalities to make the message seem more friendly and approachable.',
    iconEmoji: '🀝',
  },
  {
    name: 'Encouraging Tone',
    description:
      'This tone would be useful for motivation and encouragement. It would include positive words, affirmations, and express support and belief in the recipient.',
    iconEmoji: 'πŸ’ͺ',
  },
  {
    name: 'Empathetic Tone',
    description:
      'This tone would be utilized to display understanding and empathy. It would involve softer language, acknowledging feelings, and demonstrating compassion and support.',
    iconEmoji: '🀲',
  },
  {
    name: 'Neutral Tone',
    description:
      'For times when you want to maintain an even, unbiased, and objective tone. It would avoid extreme language and emotive words, opting for clear, straightforward communication.',
    iconEmoji: '😐',
  },
  {
    name: 'Assertive Tone',
    description:
      'This tone is beneficial for making clear points, standing ground, or in negotiations. It uses direct language, is confident, and does not mince words.',
    iconEmoji: 'πŸ”¨',
  },
  {
    name: 'Instructive Tone',
    description:
      'This tone would be useful for tutorials, guides, or other teaching and training materials. It is clear, concise, and walks the reader through steps or processes in a logical manner.',
    iconEmoji: 'πŸ“–',
  },
  {
    name: 'Persuasive Tone',
    description:
      'This tone can be used when trying to convince someone or argue a point. It uses persuasive language, powerful words, and logical reasoning.',
    iconEmoji: '☝️',
  },
  {
    name: 'Sarcastic/Ironic Tone',
    description:
      'This tone can make the communication more humorous or show an ironic stance. It is harder to implement as it requires the AI to understand nuanced language and may not always be taken as intended by the reader.',
    iconEmoji: '😏',
  },
  {
    name: 'Poetic Tone',
    description:
      'This would add an artistic touch to messages, using figurative language, rhymes, and rhythm to create a more expressive text.',
    iconEmoji: '🎭',
  },
],
// …

Step 5: Let’s put it all together. Here is how the complete example looks:

import React, { useState, useEffect } from 'react';

import { AITranslateSettings, QBAITranslate } from 'qb-ai-translate';
import {AIRephraseSettings, QBAIRephrase} from "qb-ai-rephrase";
import {AIAnswerAssistantSettings, QBAIAnswerAssistant} from "qb-ai-answer-assistant";

interface Message {
  role: string;
  content: string;
}

const App: React.FC = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();

    if (inputValue.trim() === '') return;

    setMessages([...messages, { role: 'user', content: inputValue }]);

  };

  useEffect(() => {
    const sendToQBLibrary = async () => {
      if (inputValue.trim() === '') return;


      try {
        const aiTranslateSettings: AITranslateSettings =
            // eslint-disable-next-line @typescript-eslint/no-unsafe-call
            QBAITranslate.createDefaultAITranslateSettings();

        aiTranslateSettings.apiKey = 'sk-...Hdqk7qJz';
        // aiTranslateSettings.language = 'Ukrainian';

        const resultTranslate: string =  await QBAITranslate.translate(
            inputValue,
            messages,
            aiTranslateSettings,
        );
        let outputTranslateMessage = { role: 'assistant', content: resultTranslate }
        setMessages([...messages, outputTranslateMessage]);
        //
        const aiRephraseSettings: AIRephraseSettings = QBAIRephrase.createDefaultAIRephraseSettings();
        aiRephraseSettings.apiKey = 'sk-...Hdqk7qJz';
        aiRephraseSettings.tone = { name : 'Poetic', description: '', iconEmoji: '' };
        QBAIRephrase.defaultTones()

        const resultRephrase: string =  await QBAIRephrase.rephrase(inputValue, messages, aiRephraseSettings);
        const outputRephraseMessage = { role: 'assistant', content: resultRephrase }
        setMessages([...messages, outputRephraseMessage]);
        //
        const aiAnswerAssistantSettings: AIAnswerAssistantSettings = QBAIAnswerAssistant.createDefaultAIAnswerAssistantSettings();
        aiAnswerAssistantSettings.apiKey = 'sk-...Hdqk7qJz';

        const resultAssistant: string =  await QBAIAnswerAssistant.createAnswer(inputValue, messages, aiAnswerAssistantSettings);
        const outputAssistantMessage = { role: 'assistant', content: resultAssistant }
        setMessages([...messages, outputAssistantMessage]);

      } catch (error) {
          console.error('Error while executing the request:', error);
      }
    };

    
    sendToQBLibrary();
    setInputValue('');
  }, [messages]);

  return (
      
{messages.map((message, index) => (
{message.role === 'user' ? You: : ChatGPT:} {message.content}
))}
setInputValue(e.target.value)} />
); }; export default App;

Conclusion

Amazing! If you have followed through this guide you should now have a good idea about each of the AI Extensions libraries available to React developers building chat applications. We examined examples of using each library, before integrating them into a simple React application to experience first-hand how we can translate or rephrase messages, as well as generate quick answer responses making chat dialogues more engaging and dynamic. By understanding the basic principles of using these libraries, you can now easily integrate them into your projects and create smart and efficient chat applications.

For those looking to delve deeper into the world of development, we recommend exploring more complex use cases with our React UI Kit and JavaScript SDK.

Additional Resources

If you wish to deepen your knowledge and skills in developing AI enhanced chat applications with React see useful links to documentation, user guides, and other online resources below:

QuickBlox React UI Kit Documentation: This official user guide provides detailed information about the capabilities and features of QuickBlox React UI Kit, including instructions on how to use it in your projects.

Supercharge Your Web Chat Apps with ChatGPT AI Answer Assist: This article explains how to use AI Answer Assist within QuickBlox React UI Kit, providing you with additional examples and ideas to enhance your chat applications.

AI Translate Implementation Guide for React: In this guide, you’ll find information on how the translation feature works within QuickBlox React UI Kit, including steps for integration and usage.

AI Rephrase Implementation Guide for React Apps: This guide will help you understand how to apply styles to responses and create personalized expressions using AI Rephrase in QuickBlox React UI Kit.

Video tutorial on Implementation of AI Answer Assist with QuickBlox React UI Kit

Have Questions? Need Support?

Join the QuickBlox Developer Discord Community, where you can share ideas, learn about our software, & get support.

Join QuickBlox Discord

Read More

Ready to get started?

QUICKBLOX
QuickBlox post-box