Introduction
Deep learning is used by ChatGPT, an advanced language model created by OpenAI, to produce text that resembles human speech. "ChatGPT" refers to the use of this technology to create chatbots and other conversational AI systems that can interact with users and offer information.
These chatbots are educated on enormous amounts of data, allowing them to comprehend the context of words and the meaning of phrases in order to provide insightful and persuading responses to a variety of themes and circumstances.
You may utilise ChatGpt for a variety of purposes and integrate it into your applications. In this article, we'll cover how to do that for Android applications.
Implement ChatGPT In Android Application
Step 1
Create a new project in the Android Studio and select an empty activity.
Step 2
Give the project a name, select the save location folder, and click on the finish button.
Step 3
Add the following dependency in the build.gradle app level file.
implementation 'com.android.volley:volley:1.2.1'
The dependency is used for caching and making a network request in Android applications.
Step 4
Create the activity_main.xml file as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" android:padding="5dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter Message"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send" />
</LinearLayout>
</LinearLayout>
Step 5
For recyclerview items, create item_message_user.xml and item_message_bot.xml in the layout folder. The first file is used when the user sends a message, and the other file is used for the chatbot's response.
item_message_user.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/text_message_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_message_user"
android:padding="16dp"
android:textColor="@android:color/white"
android:textSize="16sp" />
</LinearLayout>
item_message_bot.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/text_message_bot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_message_bot"
android:padding="16dp"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
Step 6
To add a border to recycleview items, create a bg_message_user.xml and a bg_message_bot.xml file in the drawable folder. The first shape is used in item_message_user.xml, and another one is used in item_message_bot.xml.
bg_message_user.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#33b5e5" />
</shape>
bg_message_bot.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f0f0f0" />
</shape>
Step 7
Create a Model class with the name Message.java to store API messages.
package com.uday.chatgptdemo;
public class Message {
private String mText;
private boolean mIsSentByUser;
public Message(String text, boolean isSentByUser) {
mText = text;
mIsSentByUser = isSentByUser;
}
public String getText() {
return mText;
}
public boolean isSentByUser() {
return mIsSentByUser;
}
}
Step 8
Create an Adapter class for recyclerview with the name MessageAdapter.java.
package com.uday.chatgptdemo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter < MessageAdapter.MessageViewHolder > {
private static final int VIEW_TYPE_USER = 0;
private static final int VIEW_TYPE_BOT = 1;
private List < Message > mMessages;
public MessageAdapter(List < Message > messages) {
mMessages = messages;
}
@NonNull
@Override
public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == VIEW_TYPE_USER) {
view = inflater.inflate(R.layout.item_message_user, parent, false);
} else {
view = inflater.inflate(R.layout.item_message_bot, parent, false);
}
return new MessageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
Message message = mMessages.get(position);
holder.bind(message);
}
@Override
public int getItemCount() {
return mMessages.size();
}
@Override
public int getItemViewType(int position) {
Message message = mMessages.get(position);
return message.isSentByUser() ? VIEW_TYPE_USER : VIEW_TYPE_BOT;
}
static class MessageViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
public MessageViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_message_user);
}
public void bind(Message message) {
if (message.isSentByUser()) {
mTextView = itemView.findViewById(R.id.text_message_user);
mTextView.setText(message.getText());
} else {
mTextView = itemView.findViewById(R.id.text_message_bot);
mTextView.setText(message.getText());
}
}
}
}
Step 9
Create a custom singleton class used to manage the Volley library's RequestQueue in an Android app with the name MySingleton.java.
package com.uday.chatgptdemo;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private static Context context;
private MySingleton(Context ctx) {
context = ctx;
requestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
return requestQueue;
}
public < T > void addToRequestQueue(Request < T > req) {
getRequestQueue().add(req);
}
}
Step 10
Generating token for API.
Visit this URL and sign up by entering your email address and password. To produce your new key, select Create a new secret key on this screen. Once a key has been generated, it must be used as a token to create an API key.
URL For Generate Secret Key: https://platform.openai.com/account/api-keys
API URL : https://api.openai.com/v1/completions
Request
{
"model": "text-davinci-003",
"prompt": "What is your name",
"max_tokens": 100,
"temperature": 1,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0
}
Response
{
"id": "cmpl-6fO8YIHGhz0Ppe7ah36OQZKB4IRw4",
"object": "text_completion",
"created": 1675322250,
"model": "text-davinci-003",
"choices": [
{
"text": "?\n\nMy name is Charlotte.",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 4,
"completion_tokens": 8,
"total_tokens": 12
}
}
In above response "text": "?\n\nMy name is Charlotte." is your main response.
Step 11
Create the MainActivity.java file as shown below.
package com.uday.chatgptdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MessageAdapter mAdapter;
private EditText mEditText;
private Button mButton;
private String apiUrl = "https://api.openai.com/v1/completions";
private String accessToken = "Enter your token here";
private List < Message > mMessages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mEditText = findViewById(R.id.edit_text);
mButton = findViewById(R.id.button);
mMessages = new ArrayList < > ();
mAdapter = new MessageAdapter(mMessages);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
callAPI();
}
});
}
private void callAPI() {
String text = mEditText.getText().toString();
mMessages.add(new Message(text, true));
mAdapter.notifyItemInserted(mMessages.size() - 1);
mEditText.getText().clear();
JSONObject requestBody = new JSONObject();
try {
//requestBody.put("model", "text-davinci-003");
//requestBody.put("prompt", text);
//requestBody.put("max_tokens", 4076);
//requestBody.put("temperature", 1);
//requestBody.put("top_p", 1);
//requestBody.put("n", 1);
//requestBody.put("stream", false);
//requestBody.put("logprobs", null);
//requestBody.put("stop", ".");
requestBody.put("model", "text-davinci-003");
requestBody.put("prompt", text);
requestBody.put("max_tokens", 100);
requestBody.put("temperature", 1);
requestBody.put("top_p", 1);
requestBody.put("frequency_penalty", 0.0);
requestBody.put("presence_penalty", 0.0);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, apiUrl, requestBody, new Response.Listener < JSONObject > () {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray choicesArray = response.getJSONArray("choices");
JSONObject choiceObject = choicesArray.getJSONObject(0);
String text = choiceObject.getString("text");
Log.e("API Response", response.toString());
//Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
mMessages.add(new Message(text.replaceFirst("\n", "").replaceFirst("\n", ""), false));
mAdapter.notifyItemInserted(mMessages.size() - 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("API Error", error.toString());
}
}) {
@Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map < String, String > headers = new HashMap < > ();
headers.put("Authorization", "Bearer " + accessToken);
headers.put("Content-Type", "application/json");
return headers;
}
@Override
protected Response < JSONObject > parseNetworkResponse(NetworkResponse response) {
return super.parseNetworkResponse(response);
}
};
int timeoutMs = 25000; // 25 seconds timeout
RetryPolicy policy = new DefaultRetryPolicy(timeoutMs, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
// Add the request to the RequestQueue
MySingleton.getInstance(this).addToRequestQueue(request);
}
}
Step 12
Include Internet permission in the manifests file.
<uses-permission android:name="android.permission.INTERNET"/>
Step 13
Now run your app. Ask anything to the bot and they reply to it.
Summary
As you can see, implementing ChatGPT in Android application is very simple.
And here I have also uploaded a demo project, so you can download it and try it for yourself.
Thank you for reading my article. Please leave your comments in the comment box below.
Enjoy Coding.