PHP调用文心一言实际是调用文心千帆API,需先用API Key和Secret Key换取2小时有效的access_token,再在请求头携带Authorization: Bearer {token}调用模型接口,不可直连或误用密钥。

PHP 不能直接调用“百度文心一言”——因为百度官方没有开放名为 文心一言 的公开 API;你实际能调用的是百度智能云平台上的 文心千帆 大模型服务(如 ernie-bot-turbo、ernie-4.0),且必须通过其 RESTful 接口 + Access Token(非固定密钥)完成认证。
为什么不能用“API Key + Secret Key”直连?
文心千帆的鉴权方式是:先用 API Key 和 Secret Key 向 https://aip.baidubce.com/oauth/2.0/token 换取短期有效的 access_token(2 小时过期),所有模型请求必须携带该 token。不存在“永久密钥直连模型接口”的用法。
- 直接在请求头写
Authorization: Bearer your_api_key→ 返回{"error":"invalid_request","error_description":"Invalid access token"} - 把
API Key当作access_token填入请求 → 返回401 Unauthorized - 未刷新 token 导致连续调用失败 → 错误码
110(access_token expired)
PHP 获取 access_token 的正确写法
必须用 curl 或 file_get_contents 发起 POST 请求到鉴权地址,并正确编码参数。注意:grant_type=client_credentials 是固定值,不能拼错。
'client_credentials',
'client_id' => $api_key,
'client_secret' => $secret_key
]);
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => ''
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);
if (isset($result['access_token'])) {
echo "access_token: " . $result['access_token'] . "\n";
echo "expires_in: " . $result['expires_in'] . " seconds\n"; // 通常为 7200
} else {
echo "获取失败:" . ($result['error_description'] ?? '未知错误');
}
?>
用 PHP 调用 ernie-bot-turbo 模型发消息
拿到 access_token 后,向 https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-bot-turbo 发送 POST 请求,body 必须是 JSON 格式,且 Content-Type 设为 application/json。常见翻车点:
立即学习“PHP免费学习笔记(深入)”;
- 忘记在 header 中加
Authorization: Bearer {access_token} - 用
http_build_query()发送 JSON body → 接口返回100(invalid parameter) -
messages数组里role写成user/assistant(正确是user和assistant,但首字母小写,大小写敏感) - 没设置
stream=false却按非流式解析响应 → 解析失败
[
['role' => 'user', 'content' => '你好']
],
'stream' => false
];
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);
if (isset($result['result'])) {
echo "回复:" . $result['result'] . "\n";
} else {
echo "调用失败:" . ($result['error_msg'] ?? '无错误信息');
}
?>
token 缓存与自动刷新建议
每次请求都重新获取 access_token 效率低,还可能触发频率限制。生产环境应缓存 token 并检查有效期,而不是硬编码或每次都重取。
- 用
file_put_contents('token.json', json_encode([...]))存本地(开发可接受) - 用 Redis 存
setex token_key 7000 "xxx"(推荐) - 发起模型请求前,先读缓存 token,若剩余有效期
- 捕获
error_code == 110时,立即刷新 token 并重试当前请求
真正麻烦的不是写几行 PHP,而是 token 生命周期管理、错误码对应处理、以及模型返回字段嵌套层级(比如 result 在顶层,而 ernie-4.0 可能返回 choices[0].message.content)。别跳过错误响应体直接读 result,先 var_dump 看清结构再说。










