In this video it shows the steps to integrate the Chat GPT APIs of “gpt-3.5-turbo” model in your Android App. It uses Android’s volley library to call the GPT APIs from the Json object.
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.chatgpt35integration;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
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.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String stringURLEndPoint = "https://api.openai.com/v1/chat/completions";
private String stringAPIKey = "sk-8pKdd8YoyxxxxxxxxxxXXXXXbkFJX2tPPkoXzpegNelf8NS5";
private String stringOutput = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
public void buttonChatGPT(View view){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("model", "gpt-3.5-turbo");
JSONArray jsonArrayMessage = new JSONArray();
JSONObject jsonObjectMessage = new JSONObject();
jsonObjectMessage.put("role", "user");
jsonObjectMessage.put("content", "Write a poem about clouds");
jsonArrayMessage.put(jsonObjectMessage);
jsonObject.put("messages", jsonArrayMessage);
} catch (JSONException e) {
throw new RuntimeException(e);
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
stringURLEndPoint, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String stringText = null;
try {
stringText = response.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content");
} catch (JSONException e) {
throw new RuntimeException(e);
}
stringOutput = stringOutput + stringText;
textView.setText(stringOutput);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> mapHeader = new HashMap<>();
mapHeader.put("Authorization", "Bearer " + stringAPIKey);
mapHeader.put("Content-Type", "application/json");
return mapHeader;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
return super.parseNetworkResponse(response);
}
};
int intTimeoutPeriod = 60000; // 60 seconds timeout duration defined
RetryPolicy retryPolicy = new DefaultRetryPolicy(intTimeoutPeriod,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(retryPolicy);
Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest);
}
}
plugins {
id 'com.android.application'
}
android {
namespace 'com.programmerworld.chatgpt35integration'
compileSdk 33
defaultConfig {
applicationId "com.programmerworld.chatgpt35integration"
minSdk 33
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'com.android.volley:volley:1.2.1'
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ChatGPT35Integration"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="157dp"
android:layout_marginTop="69dp"
android:onClick="buttonChatGPT"
android:text="Chat GPT"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Screenshots:
![](https://programmerworld.co/wp-content/uploads/2023/07/image-6-1024x544.png)
![](https://programmerworld.co/wp-content/uploads/2023/07/image-5-1024x544.png)
![](https://programmerworld.co/wp-content/uploads/2023/07/image-4-1024x544.png)