PHP调用OpenAI Completions API获取响应异常问题求助
PHP调用OpenAI API问题排查与修复
核心问题分析
你的代码存在3个关键问题,直接导致响应异常:
- JSON格式错误:
stop参数里的'\n'用了单引号,JSON无法识别为换行符,需改为双引号包裹的"\n";代码中的"是HTML转义字符,实际运行时要替换为真实双引号。 - 字符串遍历错误:
$response->choices[0]->text本身是字符串,而非数组,foreach循环会把字符串拆成单个字符拼接,导致返回内容混乱。 - 模型兼容性问题:
davinci属于旧版GPT-3模型,当前OpenAI推荐使用gpt-3.5-turbo-instruct作为completions接口的替代模型,旧模型可能存在响应质量或可用性问题。
修复后的完整代码
function generate_response($input) { $openai_api_key = "MY TOKEN"; // 替换为你的真实API密钥 $prompt = "Answer the following question: " . $input; $data = array( 'prompt' => $prompt, 'max_tokens' => 1000, 'temperature' => 0.5, 'model' => 'gpt-3.5-turbo-instruct', 'stop' => ["\n"], ); $url = 'https://api.openai.com/v1/completions'; $headers = array( 'Content-Type: application/json', 'Authorization: Bearer ' . $openai_api_key ); $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 生产环境建议保留SSL验证 $response_raw = curl_exec($ch); // 调试用:取消注释可查看API原始返回内容 // var_dump($response_raw); $response = json_decode($response_raw); curl_close($ch); if (isset($response->error)) { return "Error: " . $response->error->message; } if (isset($response->choices[0]->text)) { return trim($response->choices[0]->text); // 去除首尾空白字符 } else { return "No valid response received"; } } $user_question = "What is the capital of France?"; $response = generate_response($user_question); echo "<h1>$response</h1>";
额外调试建议
- 取消代码中
var_dump($response_raw);的注释,查看API返回的原始内容,排查是否存在密钥权限、模型调用限制等问题。 - 确认API密钥已正确替换,且该密钥拥有调用
completions接口的权限。 - 若响应仍不符合预期,可调整
temperature参数(0更精准,1更发散)或max_tokens参数控制响应长度。
内容的提问来源于stack exchange,提问作者Royal Coder
相关产品推荐
相关产品推荐

