TaskSystem/app/api/controller/XunFeiController.php

111 lines
3.4 KiB
PHP
Raw Normal View History

2023-09-12 12:36:32 +08:00
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台PHP版
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用可去除界面版权logo
// | gitee下载https://gitee.com/likeshop_gitee/likeadmin
// | github下载https://github.com/likeshop-github/likeadmin
// | 访问官网https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\controller;
2023-09-12 15:20:31 +08:00
use IFlytek\Xfyun\Speech\ChatClient;
use WebSocket\Client;
2023-09-12 12:36:32 +08:00
/**
* 讯飞
* Class WechatController
*/
class XunFeiController extends BaseApiController
{
public array $notNeedLogin = ['ceshi'];
private $app_id='2eda6c2e';
2023-09-12 15:20:31 +08:00
private $api_key='12ec1f9d113932575fc4b114a2f60ffd';
2023-09-12 12:36:32 +08:00
2023-09-12 15:20:31 +08:00
private $api_secret='MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2';
2023-09-12 12:36:32 +08:00
2023-09-12 15:20:31 +08:00
public function chat()
2023-09-12 12:36:32 +08:00
{
2023-09-12 15:20:31 +08:00
$chat=new ChatClient($this->app_id,$this->api_key,$this->api_secret);
$client = new Client($chat->assembleAuthUrl('wss://spark-api.xf-yun.com/v2.1/chat'));
// 连接到 WebSocket 服务器
if ($client) {
// 发送数据到 WebSocket 服务器
$data = $this->getBody($this->app_id,"你是谁?");
$client->send($data);
// 从 WebSocket 服务器接收数据
$answer = "";
while(true){
$response = $client->receive();
$resp = json_decode($response,true);
$code = $resp["header"]["code"];
echo "从服务器接收到的数据: " . $response;
if(0 == $code){
$status = $resp["header"]["status"];
if($status != 2){
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
}else{
$content = $resp['payload']['choices']['text'][0]['content'];
$answer .= $content;
$total_tokens = $resp['payload']['usage']['text']['total_tokens'];
print("\n本次消耗token用量\n");
print($total_tokens);
break;
}
}else{
echo "服务返回报错".$response;
break;
}
}
print("\n返回结果为:\n");
print($answer);
} else {
echo "无法连接到 WebSocket 服务器";
}
2023-09-12 12:36:32 +08:00
}
2023-09-12 15:20:31 +08:00
//构造参数体
function getBody($appid,$question){
$header = array(
"app_id" => $appid,
"uid" => "1"
);
$parameter = array(
"chat" => array(
"domain" => "generalv2",
"temperature" => 0.5,
"max_tokens" => 1024
)
);
$payload = array(
"message" => array(
"text" => array(
array("role" => "user", "content" => $question)
)
)
);
$json_string = json_encode(array(
"header" => $header,
"parameter" => $parameter,
"payload" => $payload
));
return $json_string;
}
2023-09-12 12:36:32 +08:00
}