PHP怎么调用智谱ChatGLM_API_封装函数请求返回对话结果【实例】

PHP调用智谱ChatGLM API需严格遵循OpenAPI规范:使用curl发送POST请求,设置Authorization头(Bearer+空格+API密钥)、Content-Type为application/json,JSON体含model、messages(格式为[{“role”:”user”,”content”:”xxx”}])、stream=false;否则易返回401或400错误。

php怎么调用智谱chatglm_api_封装函数请求返回对话结果【实例】

PHP 调用智谱 ChatGLM API 的核心是 curl 发送 POST 请求

智谱 AI(Zhipu AI)的 ChatGLM 系列模型(如 glm-4glm-3-turbo)不提供原生 PHP SDK,必须手动构造 HTTP 请求。关键不是“封装成函数”,而是确保请求头、认证方式、JSON 体结构完全符合其 OpenAPI 规范——否则直接返回 401 Unauthorized400 Bad Request

常见错误包括:Authorization 头漏了 Bearer 前缀、Content-Type 没设为 application/jsonmessages 数组格式不合法(必须是 [{"role": "user", "content": "xxx"}])、model 字段写错(比如写成 chatglm3 而非官方文档写的 glm-3-turbo)。

必须设置的请求头和参数字段

智谱 API 要求严格校验以下字段,缺一不可:

  • Authorization: Bearer —— 注意 Bearer 后带空格,your_api_key 是你在 open.bigmodel.cn 生成的密钥
  • Content-Type: application/json
  • POST body 必须是 JSON 字符串,且包含:model(字符串)、messages(消息数组)、stream(布尔值,设为 false 才能一次性拿到完整响应)
  • messages 中每条必须有 role"user""assistant")和 content(字符串),不能为 null 或空字符串

一个可直接运行的 PHP 封装函数示例

该函数只做最小必要封装:接收 $api_key$prompt$model,返回原始 JSON 响应或 false。不处理重试、超时自适应、流式解析等进阶逻辑——那些容易掩盖真实错误。

Stenography

Stenography

一个AI驱动的代码库API

下载

立即学习PHP免费学习笔记(深入)”;

function call_zhipu_chatglm($api_key, $prompt, $model = 'glm-4') {
    $url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'model' => $model,
        'messages' => [['role' => 'user', 'content' => $prompt]],
        'stream' => false
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $api_key,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code !== 200 || $response === false) {
        return false;
    }
    
    return json_decode($response, true);
}

// 使用示例:
$result = call_zhipu_chatglm('your_api_key_here', '你好,请用中文简单介绍你自己');
if ($result && isset($result['choices'][0]['message']['content'])) {
    echo $result['choices'][0]['message']['content'];
} else {
    echo '调用失败或响应格式异常';
}

返回结果解析和常见陷阱

成功响应的 JSON 结构固定,但新手常在这里出错:

  • $result['choices'][0]['message']['content'] 是你要的文本,但必须先判空——choices 可能为空数组(如配额用尽)
  • 如果返回 {"error":{"code":"invalid_apikey","message":"Invalid API Key"}},说明 Authorization 头格式错或密钥无效
  • 如果返回 {"error":{"code":"rate_limit_exceeded","message":"Rate limit exceeded"}},不是代码问题,是账号免费额度已用完,需升级或等重置
  • 不要尝试用 file_get_contents() + stream_context_create() 替代 curl —— 智谱 API 对 ConnectionTransfer-Encoding 敏感,curl 更可控

真正难的不是写函数,而是把错误响应里的 error.code 和文档一一对照;很多“调不通”其实只是密钥没权限调用指定模型,或者模型名拼错了。

https://www.php.cn/faq/1976194.html

发表回复

Your email address will not be published. Required fields are marked *