PHP 文心千帆API接口对接

一:API 调用流程简介

  1. 创建一个智能云应用。根据实际需求创建智能云应用。创建成功后,获取AppID、API Key、Secret Key 等信息。
  2. API 授权。对应用的 AppID 进行授权。
  3. 获取接口访问凭证 access_token 。根据第1步获取的 API Key 和 Secret Key ,
    获取 access_token ,通过 access_token 鉴权调用者身份。
  4. 调用API接口。调用创建chat接口,详见本文说明。

二:具体功能实现

Chat.php

php 复制代码
<?php
namespace bdchat;
class Chat {

    private $client_id;// API Key
    private $client_secret;// Secret Key
    private $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;
    }
}

这里我使用的是多轮

php 复制代码
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 可能会遇到的问题

最开始对接的时候,提示以下错误信息:(无权限访问该用户数据。)

php 复制代码
{"error_code":6,"error_msg":"No permission to access data"}

首先这种问题需要考虑创建应用是否勾选相关接口权限。

相关推荐
m0_748240253 分钟前
python轻量级框架-flask
开发语言·python·flask
论迹15 分钟前
【JavaEE】-- 多线程(初阶)2
java·开发语言·java-ee
+72025 分钟前
如何在java中用httpclient实现rpc post 请求
java·开发语言·rpc
学习两年半的Javaer34 分钟前
Rust语言基础知识详解【一】
开发语言·rust
PyAIGCMaster34 分钟前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
全栈开发圈35 分钟前
新书速览|Rust汽车电子开发实践
开发语言·rust·汽车
PyAIGCMaster37 分钟前
第二周补充:Go语言中&取地址符与fmt函数详解
开发语言·后端·golang
~kiss~42 分钟前
Rust学习~tokio简介
开发语言·学习·rust
Mr.Wang8091 小时前
条款23:宁以non-member、non-friend替换member函数
开发语言·c++
关关钧1 小时前
【R语言】读取CSV数据时,显示[1] PK...<0 行> (或0-长度的row.names)
开发语言·r语言