一:API 调用流程简介
- 创建一个智能云应用。根据实际需求创建智能云应用。创建成功后,获取AppID、API Key、Secret Key 等信息。
- API 授权。对应用的 AppID 进行授权。
- 获取接口访问凭证 access_token 。根据第1步获取的 API Key 和 Secret Key ,
获取 access_token ,通过 access_token 鉴权调用者身份。 - 调用API接口。调用创建chat接口,详见本文说明。
二:具体功能实现
Chat.php
<?php
namespace bdchat;
class Chat {private $client_id;// API Keyprivate $client_secret;// Secret Keyprivate $message;// 聊天上下文信息public function __construct($client_id, $client_secret) {$this->client_id = $client_id;$this->client_secret = $client_secret;}public function runErnieBot($message) {$curl = curl_init();curl_setopt_array($curl, array(CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={$this->getAccessToken()}",CURLOPT_TIMEOUT => 30,CURLOPT_RETURNTRANSFER => true,CURLOPT_CUSTOMREQUEST => 'POST',CURLOPT_POSTFIELDS =>$message,CURLOPT_HTTPHEADER => array('Content-Type: application/json'),));$response = curl_exec($curl);curl_close($curl);return $response;}public function runErnieBotTurbo($message) {$curl = curl_init();curl_setopt_array($curl, array(CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token={$this->getAccessToken()}",CURLOPT_TIMEOUT => 30,CURLOPT_RETURNTRANSFER => true,CURLOPT_CUSTOMREQUEST => 'POST',CURLOPT_POSTFIELDS =>$message,CURLOPT_HTTPHEADER => array('Content-Type: application/json'),));$response = curl_exec($curl);curl_close($curl);return $response;}/*** 使用 AK,SK 生成鉴权签名(Access Token)* @return string 鉴权签名信息(Access Token)*/private function getAccessToken(){$curl = curl_init();curl_setopt_array($curl, array(CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=".$this->client_id."&client_secret=".$this->client_secret."&grant_type=client_credentials",CURLOPT_TIMEOUT => 30,CURLOPT_RETURNTRANSFER => true,CURLOPT_CUSTOMREQUEST => 'POST',CURLOPT_HTTPHEADER => array('Content-Type: application/json','Accept: application/json'),));$response = curl_exec($curl);curl_close($curl);$rtn = json_decode($response);return $rtn->access_token;}
}
这里我使用的是多轮
public function run() {$user_id = 1;//用户ID$msg = "如何成为更好的人";//用户聊天内容$is_stream = 0;//是否以流式接口的形式返回数据,默认false。$cacheKey = $user_id.'@chatlog';// 缓存文件名$old_content = cache($cacheKey);include_once CMF_ROOT . 'vendor/baidubce/Chat.php';$chat = new Chat('ClientId','ClientSecret');//自行更改一下配置$messages = [];$my_msg = [];$my_msg['role'] = 'user';$my_msg['content'] = $msg;if (!$old_content) {// 之前该用户没有存在聊天记录$messages['messages'][] = $my_msg;} else {// 之前有聊天记录$messages = json_decode($old_content,true);$messages['messages'][] = $my_msg;}$messages['stream'] = $is_stream == 1 ? true : false;$data = json_encode($messages,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);$response = $chat->runErnieBotTurbo($data);$res = [];if ($is_stream == 1) {$str_arr = explode("data: ",$response);array_shift($str_arr);$res_msg = [];for ($i=0; $i < count($str_arr); $i++) {$arr = [];$arr = json_decode($str_arr[$i],true);$res_msg[] = $arr['result'];}$res['result'] = implode("\n\n",$res_msg);} else {$res = json_decode($response,true);}$assistant_msg = [];$assistant_msg['role'] = 'assistant';$assistant_msg['content'] = $res['result'];$messages['messages'][] = $assistant_msg;cache($cacheKey,json_encode($messages));$this->success('请求成功!',$messages);
}
三:相关问题
01 单轮与多轮的区别
多轮的需要在请求参数中将之前发送与返回的数据也加上,上面的代码示例是用的多轮,不过推荐大家使用单轮响应的方式。
02 注意流式接口返回数据与其他不同,需要对数据进行处理
03 可能会遇到的问题
最开始对接的时候,提示以下错误信息:(无权限访问该用户数据。)
{"error_code":6,"error_msg":"No permission to access data"}
首先这种问题需要考虑创建应用是否勾选相关接口权限。