由于 okhttp3.internal.http.RealResponseBody 导致无法加载消息

问题描述 投票:0回答:1

我正在尝试将 chatgpt 实现到我的 Android 应用程序中。

当我向 chatgpt 发送消息时,它回复我错误“由于 okhttp3.internal.http.RealResponseBody 导致无法加载消息”

这是我正在使用的代码:


public class GPTActivity extends DrawerBaseActivity {

    private ActivityGptactivityBinding activityGptactivityBinding;
    private RecyclerView recyclerViewGPT;
    private TextView welcomeTextView;
    private EditText messageEditText;
    private ImageButton sendButton;

    private GPTAdapter gptAdapter;
    private List<Message> messageList;

    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityGptactivityBinding = activityGptactivityBinding.inflate(getLayoutInflater());
        setContentView(activityGptactivityBinding.getRoot());
        allocateActivityTitle("ChatGPT");

        messageList = new ArrayList<>();

        recyclerViewGPT = findViewById(R.id.recyclerviewGPT);
        welcomeTextView = findViewById(R.id.welcome_text);
        messageEditText = findViewById(R.id.message_edit_Text);
        sendButton = findViewById(R.id.send_btn);

        gptAdapter = new GPTAdapter(messageList);
        recyclerViewGPT.setAdapter(gptAdapter);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setStackFromEnd(true);
        recyclerViewGPT.setLayoutManager(llm);

        sendButton.setOnClickListener((v) -> {
            String question = messageEditText.getText().toString().trim();
            addToChat(question, Message.SENT_BY_USER);
            messageEditText.setText("");
            callAPI(question);
            welcomeTextView.setVisibility(View.GONE);
        });
    }

    void addToChat(String message, String sentBy){
        runOnUiThread(new Runnable() {
            @Override
                public void run(){
                    messageList.add(new Message(message, sentBy));
                    gptAdapter.notifyDataSetChanged();
                    recyclerViewGPT.smoothScrollToPosition(gptAdapter.getItemCount());
            }
        });
    }

    void addResponse(String response){
        messageList.remove(messageList.size()-1);
        addToChat(response, Message.SENT_BY_BOT);
    }

    void callAPI(String question){

        messageList.add(new Message("Typing... ",Message.SENT_BY_BOT));

        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("model", "text-davinci-003");
            jsonBody.put("prompt", question);
            jsonBody.put("max_tokens", 4000);
            jsonBody.put("temperature", 0);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        RequestBody body = RequestBody.create(jsonBody.toString(), JSON);
        Request request = new Request.Builder()
                .url("https://api.openai.com/v1/completions").
                header("Authorization", "Bearer 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").
                post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                addResponse("Failed to load message due to " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if(response.isSuccessful()){
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.body().string());
                        JSONArray jsonArray = jsonObject.getJSONArray("choices");
                        String result = jsonArray.getJSONObject(0).getString("text");
                        addResponse(result.trim());
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }

                }else{
                    addResponse("Failed to load message due to " + response.body().toString());
                }
            }
        });
    }
}



public class GPTAdapter extends RecyclerView.Adapter<GPTAdapter.GptViewHolder> {

    List<Message> messageList;
    public GPTAdapter(List<Message> messageList) {
        this.messageList = messageList;

    }

    @NonNull
    @Override
    public GptViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View chatView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item, null);
        GptViewHolder gptViewHolder = new GptViewHolder(chatView);
        return gptViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull GptViewHolder holder, int position) {
        Message message = messageList.get(position);
        if(message.getSentBy().equals(Message.SENT_BY_USER)) {
            holder.leftChatView.setVisibility(View.GONE);
            holder.rightChatView.setVisibility(View.VISIBLE);
            holder.rightTextView.setText(message.getMessage());
        }else{
            holder.rightChatView.setVisibility(View.GONE);
            holder.leftChatView.setVisibility(View.VISIBLE);
            holder.leftTextView.setText(message.getMessage());

        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public class GptViewHolder extends RecyclerView.ViewHolder{

        LinearLayout leftChatView, rightChatView;
        TextView leftTextView, rightTextView;

        public GptViewHolder(@NonNull View itemView) {
            super(itemView);
            leftChatView = itemView.findViewById(R.id.left_chat_view);
            rightChatView = itemView.findViewById(R.id.right_chat_view);
            leftTextView = itemView.findViewById(R.id.left_chat_text_view);
            rightTextView = itemView.findViewById(R.id.right_chat_text_view);
        }
    }
}

我尝试查看具有相同错误的帖子,但建议的修复对我不起作用。

android okhttp chatgpt-api
1个回答
0
投票

您的通话中存在一些问题:

  • 您正在使用现已过时的完成 API。使用助手 API

  • 正确的网址是:https://api.openai.com/v1/chat/completions(您的网址中缺少聊天)

  • JSon 格式应如下:

    { “型号”:“gpt-3.5-turbo”, “消息”:[ { “角色”:“系统”, "content": "你是一个有用的助手。" }, { “角色”:“用户”, "content": "{此处显示您的提示}" } ] }

© www.soinside.com 2019 - 2024. All rights reserved.