chat with ChatGPT using android studio java code

To incorporate the ChatGPT  Chat API into an Android Studio project using Java code, you can proceed as below.

Set up the project:

1>     Create a new Android Studio project or open an existing one.

 

2>     For  internet permission in your AndroidManifest.xml file add below code:

        <uses-permission android:name="android.permission.INTERNET" />

3>     Add the  dependencies:  Open your app-level build.gradle file and add the following dependency I sue volly: 

implementation 'com.android.volley:volley:1.2.1'
        Create Activity page : ChatActivity
Add code below:
 
private ActivityChatBinding binding;
private static final String API_KEY = " YOUR_OWNAPI_KEY ";
private static final String API_URL = "https://api.openai.com/v1/completions";
 
 call Oncreate method : sendMessage(pass message or query u have)
 
private void sendMessage(String message) {
   
JSONObject jsonBody=new JSONObject();
   
try {
       
jsonBody.put("model","text-davinci-003");
       
jsonBody.put("prompt",message);
       
jsonBody.put("max_tokens",100);
       
jsonBody.put("temperature",0);
    }
catch (JSONException e) {
       
throw new RuntimeException(e);
    }

   
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
           
Request.Method.POST, API_URL, jsonBody,
           
new Response.Listener<JSONObject>() {
               
@Override
               
public void onResponse(JSONObject stringResponse) {
                   
//Log.d("onResponse"," : "+stringResponse.toString());
                   
JSONObject jsonObject = null;
                   
try {
                       
jsonObject = new JSONObject(stringResponse.toString());
                       
JSONArray choicesArray = jsonObject.getJSONArray("choices");
                       
String generatedMessage = choicesArray.getJSONObject(0).getString("text");
                       
Log.d("onResponse"," : "+generatedMessage);
                      

                    }
catch (JSONException e) {
                       
throw new RuntimeException(e);
                    }


                }
            },
new Response.ErrorListener() {
       
@Override
       
public void onErrorResponse(VolleyError error) {
            
Log.d("onResponse : ",""+error.toString());

        }
    }) {


       
// Passing some request headers
       
@Override
       
public Map<String, String> getHeaders() throws AuthFailureError {
           
HashMap<String, String> headers = new HashMap<String, String>();
           
headers.put("Content-Type", "application/json; charset=utf-8");
           
headers.put("Authorization", "Bearer "+API_KEY);

           
return headers;
        }

    };

   
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
           
0,
           
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
           
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

   
// Adding request to request queue
   
Volley.newRequestQueue(this).add(jsonObjReq);


}
 

Remember to replace " YOUR_OWNAPI_KEY " in the OpenAIChatApi class with your actual OpenAI API key otherwise you get errror.

 

To get an API key for the ChatGPT  API,Go to the OpenAI website: Visit the OpenAI website at https://openai.com/.

Sign in an account using your information. Access the API section: Once you're logged in, navigate to the API section of the OpenAI platform. You can usually find it in the top navigation menu and “View API Key”

You can create API key and use it.

For full code can check here:  https://github.com/nipamaity/ChatGptAndroid 

Comments

Popular posts from this blog

Create XL sheet using kotlin and poi in android

Android Kotlin code for Create folder With Real-Time Permissions

Adding Multilingual Support in Kotlin Android Apps