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

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

相关推荐
心情好的小球藻29 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己41 分钟前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
笑衬人心。1 小时前
TCP 拥塞控制算法 —— 慢启动(Slow Start)笔记
笔记·tcp/ip·php
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)9 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java9 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展