开发类ChatGPT应用遇OpenAI API错误:Invalid URL (POST /chat/v1/completions)
排查OpenAI API请求的无效URL错误
错误信息
Failed to load response due to { 'error' : { 'message' : 'Invalid URL (POST /chat/v1/completions)', 'type':'invalid_request_error', 'param':null, 'code':null } }
问题分析与修正方案
1. API端点URL错误(核心问题)
你当前使用的URL路径顺序完全错误:
- 错误URL:
https://api.openai.com/chat/v1/completions - 正确URL(对应gpt-3.5-turbo模型):
https://api.openai.com/v1/chat/completions
注意:如果直接移除/chat/改成https://api.openai.com/v1/completions,这是旧版文本模型(如text-davinci-003)的端点,和gpt-3.5-turbo不兼容,所以也会报错。
2. 确保messages参数格式正确
gpt-3.5-turbo要求messages是JSON数组,每个元素必须包含role(可选值:user/assistant/system)和content字段。如果你的question只是字符串,会导致请求格式错误,修正示例:
// 替换原有的jsonBody.put("messages", question); JSONArray messages = new JSONArray(); messages.put(new JSONObject().put("role", "user").put("content", "你的具体问题内容")); jsonBody.put("messages", messages);
3. 其他验证点
- 确认
Authorization头格式:Bearer和密钥之间必须有空格 - 检查你的API密钥是否有效、额度充足
修正后的核心代码片段
JSONObject jsonBody = new JSONObject(); try { jsonBody.put("model", "gpt-3.5-turbo"); // 构造正确的messages数组 JSONArray messages = new JSONArray(); messages.put(new JSONObject().put("role", "user").put("content", "你的问题内容")); jsonBody.put("messages", messages); 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() // 使用正确的API端点 .url("https://api.openai.com/v1/chat/completions") .addHeader("Authorization", "Bearer HIDDEN_KEY") .addHeader("Content-Type", "application/json") .post(body) .build();
内容的提问来源于stack exchange,提问作者Kannengieser Lucas
相关产品推荐
相关产品推荐

