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
}
}