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"}

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

相关推荐
iCxhust1 小时前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo1 小时前
ES6笔记2
开发语言·前端·javascript
emplace_back2 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk2 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶3 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl3 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~3 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
nananaij3 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
阿蒙Amon3 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#