PHP无依赖调用ChatGPT API报错:messages参数类型不符求助
调用ChatGPT API时messages参数类型错误问题
问题脚本
$apiKey = "Your-API-Key"; $url = 'https://api.openai.com/v1/chat/completions'; $headers = array( "Authorization: Bearer {$apiKey}", "OpenAI-Organization: YOUR-ORG-STRING", "Content-Type: application/json" ); // Define messages $messages = array(); $messages["role"] = "user"; $messages["content"] = "Hello future overlord!"; // Define data $data = array(); $data["model"] = "gpt-3.5-turbo"; $data["messages"] = $messages; $data["max_tokens"] = 50; // init curl $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); if (curl_errno($curl)) { echo 'Error:' . curl_error($curl); } else { echo $result; } curl_close($curl);
API返回错误
{"model":"gpt-3.5-turbo","messages":{"role":"user","content":"Hello future overlord!"},"max_tokens":50}{ "error": { "message": "{'role': 'user', 'content': 'Hello future overlord!'} is not of type 'array' - 'messages'", "type": "invalid_request_error", "param": null, "code": null } }
问题原因与解决方法
问题出在$messages的定义上:你将$messages定义成了单个关联数组(键值对结构),但ChatGPT API要求messages参数必须是包含消息对象的数组(哪怕只有一条消息)。
错误写法分析
你的代码中:
$messages = array(); $messages["role"] = "user"; $messages["content"] = "Hello future overlord!";
这段代码生成的是单个关联数组,经过json_encode后会变成JSON对象:{"role":"user","content":"Hello future overlord!"},不符合API要求的数组类型。
正确写法
需要把单个消息对象放进数组中:
// 方式1:分步赋值 $messages = array(); $messages[] = array( "role" => "user", "content" => "Hello future overlord!" ); // 方式2:简洁写法 $messages = [ ["role" => "user", "content" => "Hello future overlord!"] ];
修改后,json_encode会将messages转为JSON数组:[{"role":"user","content":"Hello future overlord!"}],API就能正确识别参数类型了。
内容的提问来源于stack exchange,提问作者Bangkokian
相关产品推荐
相关产品推荐

