Files
xianyan/docs/toolsapi/application/api/controller/Demo.php
Developer b6441a8919 api
2026-04-27 23:47:18 +08:00

193 lines
8.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use think\Cache;
use think\Request;
use think\Config;
use QL\QueryList;
/**
* 示例接口
*/
class Demo extends Api
{
// 无需登录的接口,*表示全部
protected $noNeedLogin = ['*'];
// 无需鉴权的接口,*表示全部
protected $noNeedRight = ['*'];
// chatGPT
public function sendPostRequest($prompt,$role,$temperature,$top,$keys = null,$model = 'gpt-3.5-turbo',$max = 3072,$api = '') {
if(empty($keys)){
return '';
}
$header = [
'Accept: application/json',
'Authorization: Bearer '.$keys,
'Content-type: application/json',
];
$postData = [
'model' => $model, //聊天模型
'temperature' => floatval($temperature),//机器人温度值
'top_p' => floatval($top),//文本多样性
'stream' => false,//非流数据
'max_tokens' => (int)$max,
'messages' => [
["role" => "system","content" => empty($role)?"我给你个设定你的版本号为chatgpt3.5请你以gpt-3.5-turbo版回答我的问题":$role],
["role" => "user","content" => $prompt]
]
];
$params = json_encode($postData);
// https://jj.baiyu521.xyz/v1/chat/completions
// http://usd.hi-cat.top/v1/
// https://api.openai-proxy.com/v1/chat/completions
// https://proxy.geekai.co/v1/chat/completions
// https://openai.wndbac.cn/v1/chat/completions
// https://one.aiskt.com/v1/chat/completions
// https://api.bosco.icu/v1/chat/completions
$curl = curl_init(empty($api)?'https://api.bosco.icu/v1/chat/completions':$api);
$options = [
CURLOPT_POST => true,//设置 cURL 请求的 HTTP 方法为 POST 方法
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $params,
CURLOPT_TIMEOUT => 120, // 设置传输超时时间为120秒
CURLOPT_CONNECTTIMEOUT => 90, // 设置连接超时时间为90秒
CURLOPT_TCP_KEEPALIVE => true,//TCP长链接开启
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
CURLOPT_RETURNTRANSFER => true,//设置是否将请求的结果以字符串形式返回
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0, // 使用 HTTP/2 协议
CURLOPT_SSL_VERIFYPEER => false, // 禁止 cURL 验证对等证书
CURLOPT_SSL_VERIFYHOST => false, // 禁止 cURL 验证主机名
];
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$text = $httpcode;
if(200 == $httpcode || 429 == $httpcode || 401 == $httpcode|| 400 == $httpcode){
$json_array = json_decode($response, true);
if( isset( $json_array['choices'][0]['message']['content'] ) ) {
if (preg_match("/500|501|502|503|504|505/", trim($json_array['choices'][0]['message']['content']))) {
$text = '';
} else {
$text = $json_array['choices'][0]['message']['content'];//成功
}
} elseif( isset( $json_array['error']['message']) ) {
if (strpos($json_array['error']['message'], "You didn't provide an API key") === 0) { //未提供API-KEY
$text = '未提供API-KEY';
}
if (strpos($json_array['error']['message'], "Rate limit reached") === 0) { //访问频率超限错误返回的code为空特殊处理一下
$text = '访问频率超限,请稍后尝试!';
}
if (strpos($json_array['error']['message'], "Your access was terminated") === 0) { //违规使用,被封禁,特殊处理一下
$text ='违规使用,被封禁';
}
if (strpos($json_array['error']['message'], "You exceeded your current quota") === 0) { //API-KEY余额不足
$text = 'API-KEY余额不足';
}
if (strpos($json_array['error']['message'], "That model is currently overloaded") === 0) { //OpenAI服务器超负荷
$text = 'OpenAI服务器超负荷';
}
if (strpos($json_array['error']['message'], "This model's maximum context length") === 0){//超出最大上下文长度
$text = '超出最大上下文长度';
}
if (strpos($json_array['error']['message'], "This key is associated with a deactivated account") === 0){
$text = '此密钥与未激活的帐户相关联';
}
if(strpos($json_array['error']['message'],"The OpenAI account associated with this API") === 0){
$text = 'OpenAI 账号已被注销或停用';
}
if(strpos($json_array['error']['message'],"Incorrect API key provided") === 0){
$text = '不正确的API';
}
} else {
$text = "";
}
}
return $text;
}
// 远程图片下载
public function remoteImageUploadAndSave($url,$fileer = 'hanzi')
{
// 初始化一个cURL会话
$ch = curl_init($url);
// 设置选项包括URL和其他cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 执行cURL会话获取远程图片数据
$imageData = curl_exec($ch);
// 关闭cURL会话
curl_close($ch);
// 如果没有获取到图片数据,返回错误信息
if (!$imageData) {
$this->error('无法获取远程图片');
}
// 解析URL返回其组成部分
$parsedUrl = parse_url($url);
// 从解析结果中获取路径部分
$path = $parsedUrl['path'];
// 使用路径部分获取文件扩展名
$fileExt = pathinfo($path, PATHINFO_EXTENSION);
// 生成保存文件名,这里以时间戳命名,你也可以根据需要修改文件名
$saveFilename = time() . '.' . $fileExt;
// 拼接保存路径TP5的上传目录
$saveDir = ROOT_PATH . 'public' . DS . 'uploads/'.$fileer;
$savePath = $saveDir . DS . $saveFilename;
// 检查目录是否存在,不存在则创建
if (!file_exists($saveDir)) {
mkdir($saveDir, 0777, true);
}
// 将图片数据保存到指定路径
$result = file_put_contents($savePath, $imageData);
// 如果保存失败,返回错误信息
if (!$result) {
$this->error('保存图片失败');
}
// 获取图片信息
$imageInfo = getimagesize($savePath);
// 获取文件大小
$fileSize = filesize($savePath);
// 获取文件的 SHA-1 散列
$fileSha1 = sha1_file($savePath);
// 将物理路径转换为相对路径
$relativePath = str_replace(ROOT_PATH . 'public', '', $savePath);
// 组装图片信息数组
$info = [
'admin_id' => 1,//管理员ID
'url' => $relativePath,//物理路径
'imagewidth' => $imageInfo[0],//宽度
'imageheight' => $imageInfo[1],//长度
'imagetype' => $fileExt,//图片类型
'mimetype' => $imageInfo['mime'],//mime类型
'filesize' => $fileSize,//图片大小
'filename' => $saveFilename,//文件名称
'sha1' => $fileSha1,
'createtime' => time(),//上传时间
'updatetime' => time(),//更新时间
'uploadtime' => time(),//上传时间
];
Db::name('attachment')->insert($info);
// 返回保存后的文件路径和图片信息
$this->success('成功下载',$relativePath);
}
}