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

PHP调用OpenAI GPT-3 API提示未提供API密钥问题求助

问题排查与修复

你的代码存在三个关键问题,直接导致了API密钥未被正确识别的错误:

1. HTTP请求头被覆盖

你连续两次调用curl_setopt($curl, CURLOPT_HTTPHEADER, ...),第二次调用会完全覆盖第一次设置的Authorization头,导致API无法接收到密钥。必须将两个请求头合并到同一个数组中。

2. 请求路径错误

当前使用的URL https://api.openai.com/v1/engines/davinci/completions 是旧版接口路径,针对text-davinci-003模型,应使用通用补全接口路径:https://api.openai.com/v1/completions。

3. 请求数据格式不匹配

你设置了Content-Type: application/json,但用http_build_query($data)生成了表单格式的数据,API无法正确解析,同时会干扰身份验证逻辑。需改用json_encode($data)生成JSON格式的请求体。

修正后的完整代码

$curl = curl_init("https://api.openai.com/v1/completions");

$data = array(
  'prompt' => 'how many sundays in 2023',
  'max_tokens' => 256,
  'temperature' => 0.7,
  'model' => 'text-davinci-003'
);

curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 合并请求头,避免覆盖
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer sk-MY-API-KEY',
    'Content-Type: application/json'
]);

$result = curl_exec($curl);
// 新增:检查curl执行是否出错
if(curl_errno($curl)) {
    echo 'Curl错误: ' . curl_error($curl);
}
curl_close($curl);

$result = json_decode($result);
// 新增:检查API返回的错误信息
if(isset($result->error)) {
    echo 'API错误: ' . $result->error->message;
} else {
    print $result->choices[0]->text;
}

额外提示

  • 新增的错误检查逻辑可以帮你快速定位后续可能出现的网络或API权限问题。
  • 确认你的API密钥拥有调用text-davinci-003模型的权限,且账户余额充足。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:25:35