исправь ошибку 2024-05-16 14:53:19.040  5350-5434  HTTP_ERROR              com.example.proxyapi                 E  Exception: Value sorry of type java.lang.String cannot be converted to JSONObject
                                                                                                    org.json.JSONException: Value sorry of type java.lang.String cannot be converted to JSONObject
                                                                                                    	at org.json.JSON.typeMismatch(JSON.java:112)
                                                                                                    	at org.json.JSONObject.<init>(JSONObject.java:172)
                                                                                                    	at org.json.JSONObject.<init>(JSONObject.java:185)
                                                                                                    	at com.example.proxyapi.MainActivity.lambda$sendRequestToOpenAI$7$com-example-proxyapi-MainActivity(MainActivity.java:122)
                                                                                                    	at com.example.proxyapi.MainActivity$$ExternalSyntheticLambda0.run(Unknown Source:2)
                                                                                                    	at java.lang.Thread.run(Thread.java:1012) в коде: package com.example.proxyapi;

import android.app.Activity;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.speech.RecognitionListener;
import android.speech.tts.TextToSpeech;
import org.json.JSONArray;
import org.json.JSONObject;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends Activity implements TextToSpeech.OnInitListener {

    private SpeechRecognizer speechRecognizer;
    private Intent recognitionIntent;
    private TextView StatusText;
    private TextView RecognizedText;
    private TextView ErrorText;
    private TextView RequestToChatGPT;
    private SpeechRecognitionListener listener;
    private TextToSpeech tts;
    private Button speakButton;
    private Button RecognizeButton;
    private Button SendToChatGPT;
    private String RT = "Начните распознавание";
    private TextView ModelUrlText;
    private static final int MY_PERMISSIONS_RECORD_AUDIO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ModelUrlText = findViewById(R.id.ModelUrlText);
        RecognizedText = findViewById(R.id.RecognizedText);
        ErrorText = findViewById(R.id.ErrorText);
        StatusText = findViewById(R.id.StatusText);
        RequestToChatGPT = findViewById(R.id.RequestToChatGPT);
        RecognizeButton = findViewById(R.id.RecognizeButton);
        speakButton = findViewById(R.id.speakButton);
        SendToChatGPT = findViewById(R.id.SendToChatGPT);

        listener = new SpeechRecognitionListener(RecognizedText, StatusText, ErrorText);

        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        speechRecognizer.setRecognitionListener(listener);

        recognitionIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        recognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        recognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

        RecognizeButton.setOnClickListener(v -> checkPermission());
        speakButton.setOnClickListener(v -> speakOut(RT));
        SendToChatGPT.setOnClickListener(v -> sendRequestToOpenAI(RT)); // Используйте новый метод здесь

        tts = new TextToSpeech(this, this);
    }

    private void sendRequestToOpenAI(String userQuery) {
        Thread thread = new Thread(() -> {
            try {
                String baseUrl = "https://api.binjie.fun/api/generateStream";
                URL url = new URL(baseUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
//                conn.setRequestProperty("Authorization", "Bearer " + Config.getApiKey());
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("origin", "https://chat.jinshutuan.com");
                conn.setRequestProperty("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);

                JSONObject message = new JSONObject();
                message.put("role", "user");
                message.put("content", "Who is the mister morden");
// message.put("content", userQuery);

                JSONArray messages = new JSONArray();
                messages.put(message);

                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("model", "gpt3");
                jsonRequest.put("messages", messages);

                String payload = jsonRequest.toString();
                runOnUiThread(() -> {
                    RequestToChatGPT.setText(payload);
                    ModelUrlText.setText(url.toString());
                });

                try (OutputStream os = conn.getOutputStream()) {
                    os.write(payload.getBytes());
                    os.flush();
                }

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    String result = response.toString();
                    JSONObject jsonResponse = new JSONObject(result);
                    String generatedText = jsonResponse.getString("data");

                    runOnUiThread(() -> {
                        TextView textView = findViewById(R.id.tvChatGPTResponse);
                        textView.setText(generatedText);
                        speakOut(generatedText);
                    });
                } else {
                    Log.e("HTTP_ERROR", "Response Code: " + responseCode);
                    String errorResponse = "HTTP Error: " + responseCode;
                    if (conn.getErrorStream() != null) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = in.readLine()) != null) {
                            response.append(responseLine.trim());
                        }
                        in.close();
                        errorResponse += " - " + response.toString();
                    }
                    String finalErrorResponse = errorResponse;
                    runOnUiThread(() -> ErrorText.setText(finalErrorResponse));
                }
            } catch (Exception e) {
                String errorMessage = "Exception: " + e.getMessage();
                runOnUiThread(() -> ErrorText.setText(errorMessage));
                Log.e("HTTP_ERROR", errorMessage, e);
            }
        });
        thread.start();
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO);
        } else {
            startVoiceRecognition();
        }
    }

    private void startVoiceRecognition() {
        speechRecognizer.startListening(recognitionIntent);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.getDefault());

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                speakButton.setEnabled(true);
            }
        } else {
            Log.e("TTS", "Initialization Failed!");
        }
    }

    private void speakOut(String text) {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
    }

    @Override
    public void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    public class SpeechRecognitionListener implements RecognitionListener {

        private TextView StatusText;
        private TextView RecognizedText;
        private TextView ErrorText;

        public SpeechRecognitionListener(TextView RecognizedText, TextView StatusText, TextView ErrorText) {
            this.StatusText = StatusText;
            this.RecognizedText = RecognizedText;
            this.ErrorText = ErrorText;
        }

        @Override
        public void onReadyForSpeech(Bundle params) {
            StatusText.setText("Готов");
        }

        @Override
        public void onBeginningOfSpeech() {
            StatusText.setText("Слушаю внимательно");
        }

        @Override
        public void onRmsChanged(float rmsdB) {}

        @Override
        public void onBufferReceived(byte[] buffer) {
            StatusText.setText("Получен буфер");
        }

        @Override
        public void onEndOfSpeech() {
            StatusText.setText("Конец речи");
        }

        @Override
        public void onError(int error) {
            ErrorText.setText("Ошибка " + error);
            RT = "Tell me about Pavel Durov";
            RecognizedText.setText(RT);
        }

        @Override
        public void onResults(Bundle results) {
            ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            RT = "Пока ничего не распознано";
            RecognizedText.setText(RT);
            StatusText.setText("Распознаем");
            if (matches != null && !matches.isEmpty() && matches.get(0) != null) {
                RT = matches.get(0);
                RecognizedText.setText(RT);
                speakOut(RT);
                sendRequestToOpenAI(RT); // Используйте новый метод здесь
            }
        }

        @Override
        public void onPartialResults(Bundle partialResults) {
            StatusText.setText("Частичные результаты");
        }

        @Override
        public void onEvent(int eventType, Bundle params) {
            StatusText.setText("Событие");
        }
    }
}