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

调用ChatGPT API出现failed to open stream错误的排查求助

解决OpenAI API 400 Bad Request错误的方案

1. 确认模型访问权限

代码中使用的gpt-4模型需要特定权限才能访问,若账号权限变更会导致请求失败。建议先替换为gpt-3.5-turbo测试:

$data = [
    "model" => "gpt-3.5-turbo", // 替换为账号有权限的模型
    // 其余参数保持不变
];

2. 捕获API详细错误信息

当前代码仅提示请求失败,无法获取OpenAI返回的具体错误原因。修改getOpenAIDescription函数,添加错误捕获逻辑:

$response = file_get_contents($url, false, $context);

if ($response === FALSE) {
    $error = error_get_last();
    echo "API请求错误: " . $error['message'] . "\n";
    // 强制获取响应内容(即使状态码错误)
    $context = stream_context_create(array_merge($options, ["http" => ["ignore_errors" => true]]));
    $errorResponse = file_get_contents($url, false, $context);
    if ($errorResponse) {
        echo "API错误详情: " . $errorResponse . "\n";
    }
    return null;
}

// 解析响应后检查错误字段
$responseData = json_decode($response, true);
if (isset($responseData['error'])) {
    echo "OpenAI返回错误: " . $responseData['error']['message'] . "\n";
    return null;
}

3. 修复请求数据与格式问题

  • JSON编码检查:确保$productName中的特殊字符不会导致JSON编码失败,添加编码校验:
$jsonData = json_encode($data);
if ($jsonData === false) {
    echo "JSON编码错误: " . json_last_error_msg() . "\n";
    return null;
}
// 将$options中的content替换为$jsonData
  • 请求头换行符:将请求头中的\n替换为标准HTTP的\r\n,避免解析异常:
"header" => "Content-Type: application/json\r\n" .
            "Authorization: Bearer $apiKey\r\n",

4. 修正数据库操作的参数错误

原代码中bind_param的参数类型和数量不匹配SQL语句,SQL仅包含两个占位符(description和productId),正确写法:

$stmt = $conn->prepare("UPDATE $tableName SET description = ?, inserted = 1 WHERE id_product = ?");
$stmt->bind_param("si", $description, $productId); // 字符串+整数,对应两个参数

优化后的完整API请求函数

function getOpenAIDescription($productName, $apiKey)
{
    $url = "https://api.openai.com/v1/chat/completions";

    $data = [
        "model" => "gpt-3.5-turbo",
        "messages" => [
            ["role" => "system", "content" => "You are a helpful assistant generating product descriptions for liquor products. You are most interested in back of bottle labels, but will also consider tasting and other information that are descriptive of the product. You will limit the descriptions generated to 200 words, knowing that these descriptions will be used as product descriptions on a liquor website."],
            ["role" => "user", "content" => "Provide a product description for: $productName"]
        ],
        "max_tokens" => 200 // 匹配200词的要求,调整token数更合理
    ];

    $jsonData = json_encode($data);
    if ($jsonData === false) {
        echo "JSON编码错误: " . json_last_error_msg() . "\n";
        return null;
    }

    $options = [
        "http" => [
            "header" => "Content-Type: application/json\r\n" .
                        "Authorization: Bearer $apiKey\r\n",
            "method" => "POST",
            "content" => $jsonData,
            "ignore_errors" => true
        ]
    ];

    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

    if ($response === FALSE) {
        $error = error_get_last();
        echo "API请求错误: " . $error['message'] . "\n";
        return null;
    }

    $responseData = json_decode($response, true);
    if (isset($responseData['error'])) {
        echo "OpenAI错误: " . $responseData['error']['message'] . "\n";
        return null;
    }

    return isset($responseData['choices'][0]['message']['content']) 
        ? trim($responseData['choices'][0]['message']['content']) 
        : (print("无法解析API响应\n"), null);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:44:53