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

AI Rephrase Implementation Guide for Android Apps

Vitaliy Dovbnya
14 Sep 2023
Android chat interface showing AI Rephrase

Imagine the ability to enhance your app’s communication by seamlessly adapting the tone and style of your messages with a single click. With QuickBlox’s new Android library – AI Rephrase– this innovative capability is within your reach. This is an incredibly simple, user-friendly, and lightweight library that works out of the box and encompasses all the essential functionalities for transforming the tone of a message.

Whether you’re aiming for a formal tone, a friendly vibe, or any other style, the Android AI Rephrase library empowers you to tailor your app’s messages effortlessly. The key highlight is that you integrate the library into any of your Android applications with what you might call just three clicks. You also have the option to create a chat app with the AI Rephrase feature by using the QuickBlox Android UI Kit.

Rephrase Message Tones Instantly

The AI Rephrase library for Android allows users to rephrase chat messages into different tones in a matter of seconds. The library already features 10 preconfigured text formatting options, which include:

  • Professional
  • Friendly
  • Encouraging
  • Empathatic
  • Neutral
  • Assertive
  • Instructive
  • Persuasive
  • Sarcastic/Ironic
  • Poetic Tone

Moreover, if the provided preset options are insufficient, you can effortlessly add your own. This process is also quite straightforward. Of course, you are also able to delete any of the options as desired.

Technical part

To use AI Rephrase, you’ll need to select the tone with which you’d like to rephrase the text and pass both the chosen tone and the text itself to the library.

The overall workflow of the library is depicted in the diagram below:

work flow of AI rephrase functionality

Let’s examine the stages of operation in more detail:

Stage 1 – Any Android application which uses the QuickBlox AI Rephrase library. The application can communicate with and use the library API.

Stage 2 – The QuickBlox AI Rephrase library which contains predefined tones and has logic for adding and removing tones. A reset mechanism is also available when a user wants to reset all tones to the default state.

The library can communicate with OpenAI through a QuickBlox Proxy Server or by a direct request.

Stage 3AQuickBlox Proxy Server which stores the OpenAI Token and works via a QuickBlox Token. We strongly recommended this flow because it offers better security and you don’t need to save the OpenAI API Token inside the application.

Stage 3BDirect request method means your data goes directly to OpenAI API without any proxy. We strongly recommend that you only use this method for development or debugging, because this variant requires you to store the OpenAI Api key within your application.

Stage 4OpenAI API, provides users with access to pre-trained AI models.

IMPLEMENTATION GUIDE

Android AI Rephrase Library
QuickBlox AI Documentation

Implementation into Any Android Application

Implementing this feature is easy. To utilize the QuickBlox AI Rephrase library, you only need to follow a few simple steps.

  1. Add the repository
  2. Add dependency
  3. Invoke Entry Point
  4. Modify tones

Step 1. Add the repository

You first need to add the repository to your existing Android application.
Open Gradle (root level) file and add the code as illustrated in the code snippet below. See the dependencyResolutionManagement section in particular:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        
      	// below we have the a link to QuickBlox AI repository
        maven {
            url= "https://github.com/QuickBlox/public-ai-releases"
        }
    }
}

Step 2. Add the dependency

Next, you need to add a dependency to the existing Android application.

Open Gradle (application level) file and add the code as illustrated in the snippet below. See the dependencies section.

dependencies {
    // some other dependencies
    
    // below we have a link to QuickBlox AI Rephrase library
    implementation "com.quickblox:android-ai-rephrase:1.0.0"
}

Version 1.0.0 can be updated to the latest version. Discover the latest release and the review the entire release history in our repository: https://github.com/QuickBlox/android-ai-releases/releases.

Step 3. Invoke entry point

The QuickBlox AI Rephrase library can be used with two different approaches. Either directly, using the library with raw Open AI token, or with a QuickBlox session token via a proxy.

Direct approach – While this method may be suitable during the development phase, (because it allows the quick testing of functionality without having to spend time rolling out the proxy server), it’s not recommended when the app is released. This is because care should always be taken to hide tokens, for example, by adding the token to the local.properties file. But this direct approach involves using an OpenAI token directly by allowing our the AI library to directly communicate with the OpenAI API.

Proxy approach – This is the preferred method. It is far more secure because the OpenAI token is encapsulated inside the proxy server. Using a QuickBlox session token, the AI library will communicate via a proxy server (not directly) with OpenAI API.

Direct Approach

To invoke the QuickBlox AI Rephrase library method you need to add necessary imports and invoke the executeByOpenAIToken method like in the code snippet below.

// below we have required imports for QuickBlox AI Rephrase library
import com.quickblox.android_ai_editing_assistant.QBAIRephrase
import com.quickblox.android_ai_editing_assistant.callback.Callback
import com.quickblox.android_ai_editing_assistant.exception.QBAIRephraseException
import com.quickblox.android_ai_editing_assistant.model.QBAIRephraseToneImpl

/*
 * some code
 */

private fun rephrase() {
        val context = this
        QBAIRephrase.init(context)

        val openAIToken = "open_ai_token"
        val tone = QBAIRephraseToneImpl("professional")
        val text = "Hi Bro. Can you help me?"
        QBAIRephrase.executeByOpenAITokenAsync(openAIToken, tone, text, object : Callback {
            override fun onComplete(result: List) {
                // here will be result as list of answers
            }

            override fun onError(error: QBAIRephraseException) {
                // oops, something goes wrong
            }
        })
    }

Proxy Method

// below we have required imports for QuickBlox AI Rephrase library
import com.quickblox.android_ai_editing_assistant.QBAIRephrase
import com.quickblox.android_ai_editing_assistant.callback.Callback
import com.quickblox.android_ai_editing_assistant.exception.QBAIRephraseException
import com.quickblox.android_ai_editing_assistant.model.QBAIRephraseToneImpl

/*
 * some code
 */

private fun rephrase() {
        val context = this
        QBAIRephrase.init(context)

        val qbToken = "quickblox_token"
        val serverProxyUrl = "https://my.proxy-server.com"
        val tone = QBAIRephraseToneImpl("professional")
        val text = "Hi Bro. Can you help me?"
        QBAIRephrase.executeByQBTokenAsync(qbToken, serverProxyUrl, tone, text, object : Callback {
            override fun onComplete(result: List) {
                // here will be result as list of answers
            }

            override fun onError(error: QBAIRephraseException) {
                // oops, something goes wrong
            }
        })
    }

We recommended using the proxy server method. Please ensure you use the latest method which you can in our repository: https://github.com/QuickBlox/qb-ai-assistant-proxy-server/releases

Step 4. Modify tones

In the QuickBlox AI Rephrase library we have QBAIRephraseTone interface.

The QBAIRephrase interface has two methods:

  • getName()
  • getSmileCode()

Both methods return string. The QuickBlox AI Rephrase library already has an implementation of the interface with class name QBAIRephraseToneImpl which you can use to build custom tones. The class has two parameters in constructor. They are: toneName (required), and smileCode (optional). As you can see, the class has only one required parameter, toneName. SmileCode is optional and can be passed.

There are 4 available methods to work with tones in QBAIRephrase entry point.

  • getAllTones()
  • addTone(tone)
  • removeTone(tone)
  • resetTones()

getAllTones() – return list of QBAIRephraseTone interface

Code snippet:

private fun getAllTones() {
        val tones: List = QBAIRephrase.getAllTones()
        //tones - it's list of implementation QBAIRephraseTone interfaces
}

addTone(tone) – add the custom tone. The parameter “tone” should be an implementation of QBAIRephraseTone. You can use QBAIRephraseToneImpl model.

Code snippet:

private fun addTone() {
        val toneName = "Philosophy" // here the name of new custom tone
        val smileCode = ":book:" // here the smile code. The parameter is optional
        val customTone: QBAIRephraseTone = QBAIRephraseToneImpl(toneName, smileCode = smileCode)
        QBAIRephrase.addTone(customTone)
}

removeTone(tone) – remove the tone. The parameter “tone” should be an implementation of QBAIRephraseTone. You can use QBAIRephraseToneImpl model.

Code snippet:

private fun removeTone() {
        val toneName = "Philosophy" // here the name of tone
        val smileCode = ":book:" // here the smile code. The parameter is optional
        val customTone: QBAIRephraseTone = QBAIRephraseToneImpl(toneName, smileCode = smileCode)
        QBAIRephrase.removeTone(customTone)
}

resetTones() – reset all tones to default 10 values which were described in the “Rephrase Message Tones Instantly” section.

Code snippet:

private fun resetTones(){
        // after invoking the method below the library will have only 10 default tones
        QBAIRephrase.resetTones()
}

Exception: In the QuickBlox AI Rephrase library you could receive QBAIRephraseException in onError callback. You can get detailed information from the message field, as shown in the code snippet below:

override fun onError(error: QBAIRephraseException) {
                // oops, something goes wrong
            }

Using AI Rephrase as a part of the Android UI Kit

The QuickBlox development team has integrated the AI Rephrase library into the QuickBlox Android UI Kit to save you time and make it easier to use the library.

To learn how to implement the QuickBlox Android UI Kit and send your first message, read our official documentation.

Also be sure that you have a QuickBlox account.

Add the repository and dependencies

Include references to the SDK repositories in your project-level build.gradle file at the root directory or to the settings.gradle file in your Android application.

Specify the URL of the QuickBlox repository where the files are stored. By following this URL, Gradle can find the SDK artifacts:

repositories {
    // below we have the link to QuickBlox UIKit repository
    maven { 
       url "https://github.com/QuickBlox/android-ui-kit-releases/raw/master/" 
    }

    // below we have the link to QuickBlox Android SDK repository
    maven {
       url "https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/" 
    } 


    // below we have the link to QuickBlox AI repository
    maven {
       url "https://github.com/QuickBlox/android-ai-releases/raw/main/"
    }
}

Next you need to add the implementation of QuickBlox dependencies in your module-level(App) build.gradle file in your Android application.

dependencies { 
    implementation "com.quickblox:android-ui-kit:0.2.4"
}

Enable/Disable AI Rephrase

By default, AI Rephrase is turned on in the UI Kit, but not configured.

Configure AI Rephrase with OpenAI Token

To configure AI Rephrase using the OpenAI Token, you need to invoke the following method in the UI Kit entry point after invoking the init() method.

val openAIToken = "open_ai_token"

QuickBloxUiKit.init(applicationContext)
QuickBloxUiKit.enableAIRephraseWithOpenAIToken(openAIToken)

Configure AI Rephrase with QuickBlox Token and Proxy server

To configure AI Rephrase with the QuickBlox token you need to invoke the following method in the UI Kit entry point after you invoke the init() method.

val serverProxyUrl = "https://my.proxy-server.com"

QuickBloxUiKit.init(applicationContext)
QuickBloxUiKit.enableAIRephraseWithQuickBloxToken(serverProxyUrl)

Disable AI Rephrase

To disable AI Rephrase you need to invoke the method in the UI Kit entry point after we invoke the init() method.

QuickBloxUiKit.init(applicationContext)

// below we disable the AI Rephrase
QuickBloxUiKit.disableAIRephrase()

How to use AI Rephrase

To make it super easy to use AI Rephrase within as part of the QuickBlox Android UI Kit, we have prepared several Rephrase use cases.

You can choose either the direct operations, or operations through a proxy approach when using the AI Rephrase Library. Both approaches are accepted in the constructor AIRephraseToneEntity, to rephrase outgoing text.

For asynchrony in the Android UI Kit, we use a Kotlin Coroutine. To this end, we use the viewModelScope to launch a new coroutine using the launch() builder.

A ViewModelScope is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared.

Learn more about, How to use Kotlin Coroutines in Android

Direct operations:

viewModelScope.launch {
   try {
     val text = "Hi Bro. Can you help me?"
     val tone = AIRephraseToneEntityImpl("Professional", "\uD83D\uDC54", ToneType.NORMAL)
     tone.setOriginalText(text)

     val resultEntity = LoadAIRephraseByOpenAITokenUseCase(toneEntity).execute()
     val rephrasedText = resultEntity?.getRephrasedText()
   } catch (exception: DomainException) {
       // error handling
   }
}

Operations through proxy:

viewModelScope.launch {
   try {
       val text = "Hi Bro. Can you help me?"
       val tone = AIRephraseToneEntityImpl("Professional", "\uD83D\uDC54", ToneType.NORMAL)
       tone.setOriginalText(text)

       val resultEntity = LoadAIRephraseByQuickBloxTokenUseCase(toneEntity).execute()
       val rephrasedText = resultEntity?.getRephrasedText()
   } catch (exception: DomainException) {
       // error handling
   }
}

That’s it! You’re all set.

Elevate Your Chat App with AI Rephrase on Android

This tutorial aims to enhance your Android chat application with the powerful AI Rephrase library. Whether you’ve chosen to integrate it as a standalone library, seamlessly weave it into your existing app, or leverage its capabilities through the Android UI Kit from QuickBlox, you’re now equipped to revolutionize the way users communicate within your app.

But the journey doesn’t end here. In addition to AI Rephrase, you have the opportunity to explore AI Answer Assist and AI Translate, further expanding the horizons of your app’s functionality.

AI Translate Implementation Guide for Android Apps

AI Answer Assist Implementation Guide for Android Apps

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