0

I am trying to stream response(word by word) of chatgpt api in android (java) by implementing async task but i get an error. I am using java's HTTPurlconnection library with input and outputstreams so that I can stream response of chatgpt as in its original interface but i get an error: You haven't provided API key although api key is correct as it works with android kotlin volley library. Where am i going wrong? Please help with this code

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.ads.AdView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class gpt extends AppCompatActivity {
EditText queryt;
TextView question;
TextView response1;
AdView mAdview;
Button queryb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gpt);

        response1 = findViewById(R.id.idTVResponse2);
        question = findViewById(R.id.idTVQuestion2);

        queryt = findViewById(R.id.edit_query2);
        queryb = findViewById(R.id.buttonPanel2);
        //ChatGPTTask GPT = new ChatGPTTask();
        queryb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatGPTTask GPT = new ChatGPTTask();
                GPT.execute(queryt.getText().toString());
                queryt.setText("");
            }
        });
    }

    public class ChatGPTTask extends AsyncTask<String, String, Void> {
        private final String TAG = ChatGPTTask.class.getSimpleName();

 private final String API_URL = "https://api.openai.com/v1/completions";
        //private final String API_KEY =API_KEY
        

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);


        }

       



        @Override
        protected Void doInBackground(String... strings) {


            try {
                String prompt = strings[0];
               
                URL url = new URL(API_URL);
                Log.d(TAG, "Authorization Header: " +url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                Log.d(TAG, "Authorization Header: " +conn);
                conn.setRequestMethod("POST");
                String authHeader = "Bearer API_KEY";
                conn.setConnectTimeout(5000);

            

                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", authHeader);

                conn.setDoOutput(true);
                Log.d(TAG, "Authorization Header: " + authHeader);
                String requestBody = "{\n" +
                        "    \"model\": \"text-davinci-003\",\n" +
                        "    \"prompt\": \"" + prompt + "\",\n" +
                        "    \"max_tokens\": 1000,\n" +
                        "    \"temperature\": 0.0,\n" +
                        "    \"top_p\": 1,\n" +
                        "    \"frequency_penalty\": 0.0,\n" +
                        //"    \"n\": 1,\n" +
                        //"    \"stop\": \"\\n\"\n" +
                        "    \"presence_penalty\": 0.0,\n" +
                        "}";

                conn.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));
               
                InputStream inputStream = conn.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    publishProgress(line);
                }

                bufferedReader.close();
                inputStream.close();
                conn.disconnect();
            } catch (IOException e) {
                Log.e(TAG, "Error: " + e.getMessage());
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            String response = values[0];
            response1.append(response);
            // TODO: handle ChatGPT's response here
            Log.d(TAG, "Response: " + response);
        }
    }
}type here

I was trying to get the response and append it to text view line by line as in chatgpt interface how it implements server sent events but actually on a preliminary basis it returns an error stating that I haven't provided API key although the format of API key entry is correct and the key itself is valid as i have tested the key already in a different application and it works there.

Error that i am getting from url:

{
    "error": {
        "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
  • `I am trying to stream response(word by word) of chatgpt api in android (java) by implementing async task but i get an error` That is all pretty irrerlevant and you are not even mentioning the error. Better change the subject to "How to provide API key to chatgpt using HttpURLConnection". – blackapps Feb 27 '23 at 11:28
  • That API you're using there is not ChatGPT. It's a different model. – Cerbrus Feb 27 '23 at 12:01
  • I already mentioned the error passively but I now have added the error quoted. – Calt Channel Feb 27 '23 at 12:08
  • This api is completions model api, the same that chatgpt uses for generative response(GPT-3) – Calt Channel Feb 27 '23 at 12:09
  • `String authHeader = "Bearer API_KEY";` is not how you insert your API key into your string. Try `String authHeader = "Bearer " + API_KEY;` – QBrute Feb 27 '23 at 15:19

2 Answers2

0

Regarding the error message, first double check that you have obtained your OpenAI API key from https://platform.openai.com/account/api-keys.

Regarding the model used, according to https://platform.openai.com/docs/api-reference/chat/create to use the "ChatGPT API" (chat completions), the model to be used is

  • gpt-3.5-turbo or
  • gpt-3.5-turbo-0301 ,

not text-davinci-003 as this model is for text completions.

In any case of the model that you decide to use, you might first verify that the http request to the OpenAI API using the correct endpoint and parameters is working correctly i.e. by using curl. Once you make it work, then might focus on implement this call in your Java code.

References

Rubén
  • 34,714
  • 9
  • 70
  • 166
0

First,you should generate an api key which is generated by https://platform.openai.com/account/api-keys.

second, you should use this api key when you post the request.

third, for this functionality, you should use mode gpt-3.5-turbo or gpt-3.5-turbo-0301 intead of text-davinci-003.

Frank
  • 59
  • 1
  • 2
  • 7