You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移GPT-3至GPT-3.5 API时遇OpenAI Chat Completions 400错误求助

问题原因分析及解决方法

核心错误原因

400错误源于请求JSON格式不符合OpenAI Chat Completions接口要求,核心问题集中在messages参数的处理:

  • 你将messages以字符串形式传入("[{'role': 'user', 'content': 'What are your functionalities?'}]"),但接口要求messages必须是JSON数组类型,而非字符串格式的数组。
  • 附带问题:硬编码查询内容未使用传入的query参数;响应解析时直接获取message对象的字符串形式,而非提取其中的content字段;API密钥未替换为实际有效值。

具体解决步骤

  • 修复messages参数格式:使用JSONArray和JSONObject构建符合接口要求的消息数组,而非传入字符串。
  • 对接用户输入:将传入的query参数作为消息内容,替代硬编码文本。
  • 修正响应解析逻辑:从message对象中提取content字段,而非直接获取整个对象的字符串。
  • 替换API密钥:将"Bearer APIKEY"中的APIKEY替换为你的OpenAI实际密钥。

修改后的完整代码

private fun getResponseTurbo(query: String) {
    questionTV.text = query
    queryEdt.setText("")
    val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
    
    // 构建符合要求的请求JSON
    val jsonObject = JSONObject().apply {
        put("model", "gpt-3.5-turbo")
        
        // 构建messages数组
        val messagesArray = JSONArray().apply {
            val userMessage = JSONObject().apply {
                put("role", "user")
                put("content", query) // 使用传入的用户查询参数
            }
            put(userMessage)
        }
        put("messages", messagesArray)
        
        put("temperature", 0)
        put("max_tokens", 48)
        put("top_p", 1)
        put("frequency_penalty", 0)
        put("presence_penalty", 0)
    }

    val postRequest = object : JsonObjectRequest(
        Method.POST, 
        url_turbo, 
        jsonObject,
        Response.Listener { response ->
            chattypingLT.visibility = View.GONE
            ll_copy_share.visibility = View.VISIBLE
            // 正确解析响应内容
            val responseMsg = response.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content")
            responseTV.text = responseMsg
        },
        Response.ErrorListener { error ->
            Log.e("TAGAPI", "Error: ${error.message}\n$error")
        }
    ) {
        override fun getHeaders(): MutableMap<String, String> {
            return hashMapOf(
                "Content-Type" to "application/json",
                "Authorization" to "Bearer YOUR_ACTUAL_API_KEY" // 替换为你的真实API密钥
            )
        }
    }

    postRequest.setRetryPolicy(object : RetryPolicy {
        override fun getCurrentTimeout(): Int = 50000
        override fun getCurrentRetryCount(): Int = 50000
        @Throws(VolleyError::class)
        override fun retry(error: VolleyError) {}
    })
    
    queue.add(postRequest)
}

额外注意事项

  • 确认url_turbo变量值为"https://api.openai.com/v1/chat/completions",避免拼写错误。
  • 检查你的API密钥是否具备足够权限和可用余额,权限或余额不足也可能触发400错误。

内容的提问来源于stack exchange,提问作者Bhavesh Thacker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 10:30:32