| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976 |
- <?php
- namespace app\index\controller;
- use think\Request;
- use think\Db;
- header("Access-Control-Allow-Origin: *"); // 允许所有来源
- header("Access-Control-Allow-Headers: Content-Type"); // 允许的请求头
- //sm4
- use Evit\PhpGmCrypto\Encryption\EvitSM4Encryption;
- class Apis extends \think\Controller
- {
- //对传入的信息进行存储并获取短令牌
- public function getToken(){
- //通过入参构建准备存入数据库的内容
- $information = request() -> param('information');
- // $information = 'eyJlbmNyeXB0ZWRCYXNlNjQiOiJibjk2UzZxQXBlanhVTHZLSExkdDJuWEtKSnUwZit1YlVYanl1a29HU2JYdEk5bGV4RVZZUDFHNkVJcnZld3ZtZTZDUDlKaGZZSjZyR1wvUyttdGd6cHlTQzVLM1JkUWZUYzdRNndsTG5XbGludEhqdFM0RTJqdHVSWlFPeXNZQmZQU0x4anE0SG13MEI2WkE4bTRLK2xVTHJIRXdlMVUyUkFuWkYzbDBqblZmZVZ0clwvaEloKzZ6VzRVeHBHRzllWll5ZGNIVVBGOCtldGRxdEJ5aHB1TWtEYXEwRmlXckRVXC9BVkJZYXdtTmt3aTZiRFdrdWtZS1JKRWhIa0Z3SDdYZVh1REdFdmFBNEs5VktiRENQQXY4cXJoT21abGFOMVNcLzhXZG5VczBaaEVKSXk4WEVmREcxZ0oxOVJuQTUzbENVTGgrZVFnbWVQXC9DYTd2MisxRmpjZUhlVERPaGRNamVWeXlhXC81VzJ1OVI0bnFcLzBxZ3R5WVkwMDBxeEZMaWVncHNReFlCMzh0bEh5M1hVeVdOMFBVbkNcL2FNV29ncGMrNTZleEtwU0liYkJGQXN4b2tsY2xZWkkwREVDaExFZzIiLCJzbUlWIjoiNXlVYjhGY0xGd1FFN0NpNyIsInB1YmxpY0tleSI6IlhsZTZMUjVvT1pKdU84Y3lYODFqbDNRdmZCeGg1ZmxzIn0';
- $askInfo['encryption'] = $information;
- $informationCut = substr($information, 0, 20);
- $time = time();
- $token = md5($informationCut.$time.rand(10000,99999));
- $askInfo['token'] = $token;
- $askInfo['time'] = $time;
-
- $information = base64UrlDecode($information);
- $information = json_decode($information);
- $information = stdClassObjToArray($information);
- if(!$information){
- $error['code'] = 6;
- $error['message'] = '非法请求,已拒绝。';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- //通过sm4进行解密
- $smIV = $information['smIV'];
- $publicKey = $information['publicKey'];
- $encryptedBase64 = $information['encryptedBase64'];
- $mapProject['public_key'] = array('eq',$publicKey);
- $privateKey = db('Project') -> where($mapProject) -> value('private_key');
- $config = [
- 'mode' => 'cbc',
- 'key' => $privateKey, // 16 字节二进制密钥
- 'iv' => $smIV, // 16 字节二进制 IV
- 'hash' => false
- ];
- $sm4 = new EvitSM4Encryption($config);
- $pass = base64_decode($encryptedBase64);
- $decrypted = $sm4->decrypt($pass);
- $decrypted = base64_decode($decrypted);
- $information = json_decode($decrypted);
- $information = stdClassObjToArray($information);
- if(!$information){
- $error['code'] = 0;
- $error['message'] = '解密错误,请核对仔细核对参数!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
-
- //请求信息整理
- $dataInsert['smIV'] = $smIV;
- $dataInsert['publicKey'] = $publicKey;
- $dataInsert['model'] = $information['model'];
- $dataInsert['network'] = $information['network'];
- $dataInsert['input'] = $information['input'];
-
- //构建数据库记录
- $askInfo['decrypt'] = json_encode($dataInsert,JSON_UNESCAPED_UNICODE);
-
- //将请求记录存储至数据库
- db('askinfo') -> insert($askInfo);
-
- //将token返回给请求端
- $success['code'] = 1;
- $success['token'] = $token;
- return json_encode($success,JSON_UNESCAPED_UNICODE);
- }
-
- //对传入的参数进行校验
- public function check(){
- $token = request() -> param('token');
- $ragId = request() -> param('ragId');
- //通过获取的token获取对应的encryption
- $mapAskInfo['token'] = array('eq',$token);
- $information = db('askinfo') -> where($mapAskInfo) -> value('encryption');
-
- $information = base64UrlDecode($information);
- $information = json_decode($information);
- $information = stdClassObjToArray($information);
- if(!$information){
- $error['code'] = 6;
- $error['message'] = '非法请求,已拒绝。';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- //通过sm4进行解密
- $smIV = $information['smIV'];
- $publicKey = $information['publicKey'];
- $encryptedBase64 = $information['encryptedBase64'];
- $mapProject['public_key'] = array('eq',$publicKey);
- $privateKey = db('Project') -> where($mapProject) -> value('private_key');
- $config = [
- 'mode' => 'cbc',
- 'key' => $privateKey, // 16 字节二进制密钥
- 'iv' => $smIV, // 16 字节二进制 IV
- 'hash' => false
- ];
- $sm4 = new EvitSM4Encryption($config);
- $pass = base64_decode($encryptedBase64);
- $decrypted = $sm4->decrypt($pass);
- $decrypted = base64_decode($decrypted);
- $information = json_decode($decrypted);
- $information = stdClassObjToArray($information);
- if(!$information){
- $error['code'] = 0;
- $error['message'] = '解密错误,请核对仔细核对参数!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
-
- //获取接口请求信息
- $model = $information['model'];
- $network = $information['network'];
- $input = $information['input'];
-
- if(!is_array($input)){
- $error['code'] = 7;
- $error['message'] = '输入内容必须为数组格式!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
-
- //判断模型是否存在
- $mapModel['model'] = array('eq',$model);
- $modelId = db('Model') -> where($mapModel) -> value('id');
- if($modelId){
- $mapModel['network'] = array('eq',$network);
- $modelId = db('Model') -> where($mapModel) -> value('id');
- //判断network参数是否正确
- if($modelId){
- //判断publicKey参数是否正确
- $mapProject['public_key'] = array('eq',$publicKey);
- $modelList = db('Project') -> where($mapProject) -> value('models');
- if($modelList){
- //判断publicKey是否具备模型权限
- $modelList = json_decode($modelList);
- if(in_array($modelId,$modelList)){
- $success['code'] = 5;
- $success['input'] = $input;
- $success['modelId'] = $modelId;
- if($ragId == 'empty'){
- $success['ragId'] = '';
- }
- else{
- //判断ragId和public是否存在关联关系
- $ragList = db('Project') -> where($mapProject) -> value('rags');
- $ragList = json_decode($ragList);
- $mapRag['ragid'] = array('eq',$ragId);
- $ragIdIncrement = db('Rag') -> where($mapRag) -> value('id');
- if(in_array($ragIdIncrement,$ragList)){
- $success['ragId'] = $ragId;
- }
- else{
- $error['code'] = 8;
- $error['message'] = '该公钥不具备该知识库权限,请联系管理员添加!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- }
- return json_encode($success,JSON_UNESCAPED_UNICODE);
- }
- else{
- $error['code'] = 4;
- $error['message'] = '该公钥不具备该模型权限,请联系管理员添加!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- }
- else{
- $error['code'] = 3;
- $error['message'] = '该公钥不正确,请核对参数“publicKey”的值!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- }
- else{
- $error['code'] = 2;
- $error['message'] = '该模型不支持该网络状态,请核对参数“network”的值!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- }
- else{
- $error['code'] = 1;
- $error['message'] = '模型不存在,请核对参数“model”的值!';
- return json_encode($error,JSON_UNESCAPED_UNICODE);
- }
- }
-
- //存储对应的回复记录
- public function reply(){
- $token = request() -> param('token');
- $reply = request() -> param('reply');
- $mapAskInfo['token'] = array('eq',$token);
- $data['reply'] = $reply;
- db('askinfo') -> where($mapAskInfo) -> update($data);
- }
-
- //供三方系统所支持的模型信息
- public function search(){
- //根据公钥查询模型列表
- $publicKey = request() -> param('publicKey');
- $mapProject['public_key'] = array('eq',$publicKey);
- $models = db('Project') -> where($mapProject) -> find();
- if($models){
- $modelList = json_decode($models['models']);
- //根据模型列表查询模型信息
- $mapModel['id'] = array('in',$modelList);
- $modelList = db('Model') -> where($mapModel) -> order('sort') -> select();
- $data['code'] = 1;
- $data['models'] = $modelList;
- return json($data,JSON_UNESCAPED_UNICODE) -> code(200);
- }
- else{
- $data['code'] = 0;
- $data['models'] = '该公钥并未配置模型权限,请联系管理员添加!';
- return json($data,JSON_UNESCAPED_UNICODE);
- }
- }
- //
- function handleChatTest() {
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- http_response_code(405); // 405 Method Not Allowed
- echo json_encode(['error' => 'Only POST requests are allowed']);
- return;
- }
- $expectedToken = 'sk-d5f7c8b1a37c4a9ba24f905927a7b3f9';
- $targetUrl = 'http://60.164.133.40:9997/v1/chat/completions';
-
- // 获取请求体和头信息
- $requestBody = file_get_contents('php://input');
- $headers = getallheaders();
- $authorizationHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';
-
- // 校验 Authorization
- if ($authorizationHeader !== 'Bearer ' . $expectedToken) {
- http_response_code(403);
- echo json_encode(['error' => 'Authorization header']);
- return;
- }
-
- // 发起代理请求
- $ch = curl_init($targetUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Authorization: ' . $authorizationHeader
- ]);
-
- // 设置回调,边接收边输出
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
- echo $data;
- // 立即刷新输出缓冲
- @ob_flush();
- @flush();
- return strlen($data);
- });
-
- // 返回响应
- header('Content-Type: application/json');
- $res = curl_exec($ch);
- if (curl_errno($ch)) {
- http_response_code(500);
- echo json_encode(['error' => 'cURL Error: ' . curl_error($ch)]);
- }
- curl_close($ch);
- }
- function handleChatapi() {
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- http_response_code(405);
- echo json_encode(['error' => 'Only POST requests are allowed']);
- return;
- }
-
- // 关闭所有缓冲,强制流式输出
- @ini_set('output_buffering', 'off');
- @ini_set('zlib.output_compression', false);
- while (ob_get_level() > 0) {
- ob_end_flush();
- }
- ob_implicit_flush(true);
-
- // 设置流式响应头
- header('Content-Type: application/json; charset=utf-8');
- header('Cache-Control: no-cache');
- header('X-Accel-Buffering: no'); // 对 Nginx 有效,关闭缓冲
-
- $expectedToken = 'sk-d5f7c8b1a37c4a9ba24f905927a7b3f9';
- $targetUrl = 'http://60.164.133.40:19997/v1/chat/completions';
-
- $requestBody = file_get_contents('php://input');
- $headers = getallheaders();
- $authorizationHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';
-
- if ($authorizationHeader !== 'Bearer ' . $expectedToken) {
- http_response_code(403);
- echo json_encode(['error' => 'Invalid Authorization header']);
- return;
- }
-
- $ch = curl_init($targetUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 0);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Authorization: ' . $authorizationHeader
- ]);
-
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
- echo $data;
- @ob_flush();
- @flush();
- return strlen($data);
- });
- $logFile = __DIR__ . '/handleChat.log';
- $timestamp = date('[Y-m-d H:i:s]');
- file_put_contents($logFile, $timestamp . ' ' .$requestBody .PHP_EOL, FILE_APPEND);
- $res = curl_exec($ch);
- if (curl_errno($ch)) {
- http_response_code(500);
- echo json_encode(['error' => 'cURL Error: ' . curl_error($ch)]);
- }
- curl_close($ch);
- $timestamp = date('[Y-m-d H:i:s]');
- file_put_contents($logFile, $timestamp . ' ' .PHP_EOL, FILE_APPEND);
- }
- function handleEmbedding() {
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- http_response_code(405);
- echo json_encode(['error' => 'Only POST requests are allowed']);
- return;
- }
-
- $expectedToken = 'sk-a9de61b8b354442a98e842d9ecf2a204';
- $targetUrl = 'http://60.164.133.40:19997/v1/embeddings';
-
- $headers = array_change_key_case(getallheaders(), CASE_LOWER);
- if (!isset($headers['authorization'])) {
- http_response_code(401);
- echo json_encode(['error' => 'Missing Authorization header']);
- return;
- }
- $authHeader = $headers['authorization'];
- if ($authHeader !== 'Bearer ' . $expectedToken) {
- http_response_code(403);
- echo json_encode(['error' => 'Invalid API token']);
- return;
- }
-
- $requestBody = file_get_contents('php://input');
-
- $ch = curl_init($targetUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 0);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'accept: application/json',
- 'Authorization: ' . $authHeader,
- ]);
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_ENCODING, ''); // 支持所有编码,防止自动解压影响
-
- $response = curl_exec($ch);
-
- if (curl_errno($ch)) {
- http_response_code(500);
- echo json_encode(['error' => 'cURL Error: ' . curl_error($ch)]);
- curl_close($ch);
- return;
- }
-
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- curl_close($ch);
-
- $responseHeaders = substr($response, 0, $headerSize);
- $responseBody = substr($response, $headerSize);
-
- // 关闭所有输出缓冲区,防止格式被修改
- while (ob_get_level()) {
- ob_end_clean();
- }
-
- // 只转发 Content-Type,避免冲突
- foreach (explode("\r\n", $responseHeaders) as $headerLine) {
- if (stripos($headerLine, 'Content-Type:') === 0) {
- header($headerLine);
- }
- }
-
- http_response_code($httpCode);
-
- // 直接原样输出响应体,不做任何json_encode或修改
- echo $responseBody;
- }
- //查询RAG列表
- public function searchRag(){
- //根据公钥查询模型列表
- $publicKey = request() -> param('publicKey');
- $mapProject['public_key'] = array('eq',$publicKey);
- $rags = db('Project') -> where($mapProject) -> find();
- if($rags){
- $ragList = json_decode($rags['rags']);
- //根据模型列表查询模型信息
- $mapRag['id'] = array('in',$ragList);
- $ragList = db('Rag') -> where($mapRag) -> select();
- $data['code'] = 1;
- $data['rags'] = $ragList;
- return json($data, JSON_UNESCAPED_UNICODE) -> code(200);
- }
- else{
- $data['code'] = 0;
- $data['models'] = '该公钥并未配置知识库权限,请联系管理员添加!';
- return json($data,JSON_UNESCAPED_UNICODE);
- }
- }
-
- //查询RAG列表
- public function searchagents(){
- //根据公钥查询模型列表
- $publicKey = request() -> param('publicKey');
- $mapProject['public_key'] = array('eq',$publicKey);
- $agents = db('Project') -> where($mapProject) -> find();
- if($agents){
- $agentsList = json_decode($agents['agents']);
- //根据模型列表查询模型信息
- $mapRag['id'] = array('in',$agentsList);
- $agentsList = db('agent') -> where($mapRag) -> select();
- $data['code'] = 1;
- $data['agents'] = $agentsList;
- return json($data,JSON_UNESCAPED_UNICODE) -> code(200);
- }
- else{
- $data['code'] = 0;
- $data['models'] = '该公钥并未配置智能体权限,请联系管理员添加!';
- return json($data,JSON_UNESCAPED_UNICODE);
- }
- }
- //检索增强接口
- public function ragData(){
- $input = request() -> param('input');
- $kid = request() -> param('kid');
- $RAGdata = [
- "username" => "test",
- "password" => "test123"
- ];
- // 调用时只需传递非 Content-Type/Accept 的 Header
- $headers = [
- 'Cache-Control: no-cache',
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- ];
- $urlRAG = "http://192.168.1.8:6039/auth/login"; // 替换为实际 URL
-
- $id = curlPostRAG($urlRAG, $RAGdata, $headers);
-
- $token = $id; // 默认启用 JSON 模式
- $token = json_decode($token);
- $token = stdClassObjToArray($token);
- $token = $token['data']['token'];
- $url = "http://192.168.1.8:6039/rag/schema"; // 替换成实际接口地址
- $data = [
- "messages" => $input, // 替换成实际用户输入
- "model" => "123", // 替换成实际模型名称
- "maxDistance" => 0.7, // 替换成实际分数(浮点数)
- "kid" => $kid // 替换成实际知识库 ID
- ];
-
- // 初始化 cURL
- $ch = curl_init();
- // 设置 cURL 选项
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据
- curl_setopt($ch, CURLOPT_POST, true); // 使用 POST 方法
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 发送 JSON 数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- "Authorization: Bearer " . $token,
- "Content-Type: application/json" // 声明请求体是 JSON
- ]);
-
- // 执行请求并获取响应
- $response = curl_exec($ch);
- // 检查是否有错误
- if (curl_errno($ch)) {
- echo "cURL 请求失败: " . curl_error($ch);
- } else {
- // 解析 JSON 响应
- //$result = json_decode($response, true);
- return $response; // 输出返回数据(prompt, vector, nearest)
- }
- // 关闭 cURL 资源
- curl_close($ch);
- }
-
- //查询生命体征数据
- public function vitalSignsData(){
- $number = request() -> param('number');
- $data["number"] = request() -> param('number');
- if(!isset($number) || $number == "" ){
- return ("未输入患者编号,请输入。");
- }
-
- $data["lowerBloodPressure"] = request() -> param('lowerBloodPressure');
- $data["upperBloodPressure"] = request() -> param('upperBloodPressure');
- $data["heartRate"] = request() -> param('heartRate');
- $data["temperature"] = request() -> param('temperature');
- $data["bloodOxygen"] = request() -> param('bloodOxygen');
- $data["breatheRate"] = request() -> param('breatheRate');
- $data["name"] = request() -> param('name');
- $data["sex"] = request() -> param('sex');
- $data["age"] = request() -> param('age');
- $data["deptName"] = request() -> param('deptName');
- $data["doctor"] = request() -> param('doctor');
-
- $alarmType = request() -> param('alarmType');
- $data["alarmType"] = request() -> param('alarmType');
- if(!isset($alarmType) || trim($alarmType) === "" || $alarmType == "" ){
- return ("未输入异常类型,请输入。");
- }
- $data = json_encode($data,JSON_UNESCAPED_UNICODE);
-
- $urlvitalsigns = "http://192.168.1.8:6039/patient/vitalSigns";
- $headers = [
- 'Content-Type: application/json'
- ];
- $response = curlPost($urlvitalsigns,$data,$headers);
-
- return $response;
- }
-
- public function test123(){
- $data["input"] = "?";
- $data["kid"] = '1947484295610253313';
- // $data = json_encode($data, JSON_UNESCAPED_UNICODE);
- // dump($data);
- // exit;
- $url = "http://192.168.1.8:3338/apis/knowledgeMessage";
- $a = curlPost($url,$data);
- return $a;
-
-
- }
-
- public function testhttp(){
- $data["token"] = "c9fce85232e25a803f3b0e17714a674b";
- $data["ragId"] = '1947484295610253313';
- // $data = json_encode($data, JSON_UNESCAPED_UNICODE);
- // dump($data);
- // exit;
- $url = "http://192.168.1.8:3340";
- $a = curlPost($url,$data);
- return $a;
-
-
- }
-
- //供三方系统的检索增强接口
- public function knowledgeMessage(){
- // $input = request() -> param('input');
- // $kid = request() -> param('kid');
- $json = file_get_contents('php://input');
- $json = json_decode($json);
- $json = stdClassObjToArray($json);
- if($json){
- $input = $json['input'];
- $kid = $json['kid'];
- }
- $count = request() -> param('count');
- // $input = $_POST['input'];
- // $kid = $_POST['kid'];
- $count = json_decode($count);
- $count = stdClassObjToArray($count);
- // echo($input);
- // exit;
- if($count){
- $input = $count['input'];
- $kid = $count['kid'];
- }
- if(!$input){
- echo '{"code":500,"msg":"cURL 请求失败: 请检查参数。","data":null}';
- exit;
- }
- if(!$kid){
- echo '{"code":500,"msg":"cURL 请求失败: 请检查参数。","data":null}';
- exit;
- }
- $RAGdata = [
- "username" => "test",
- "password" => "test123"
- ];
- // 调用时只需传递非 Content-Type/Accept 的 Header
- $headers = [
- 'Cache-Control: no-cache',
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- ];
-
- $urlRAG = "http://192.168.1.8:6039/auth/login"; // 替换为实际 URL
- $id = curlPostRAG($urlRAG, $RAGdata, $headers);
-
- $token = $id; // 默认启用 JSON 模式
- $token = json_decode($token);
- $token = stdClassObjToArray($token);
- $token = $token['data']['token'];
- $url = "http://192.168.1.8:6039/rag/schema"; // 替换成实际接口地址
- $data = [
- "messages" => $input, // 替换成实际用户输入
- "model" => "123", // 替换成实际模型名称
- "maxDistance" => 0.7, // 替换成实际分数(浮点数)
- "kid" => $kid // 替换成实际知识库 ID
- ];
- // 初始化 cURL
- $ch = curl_init();
- // 设置 cURL 选项
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据
- curl_setopt($ch, CURLOPT_POST, true); // 使用 POST 方法
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 发送 JSON 数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- "Authorization: Bearer " . $token,
- "Content-Type: application/json" // 声明请求体是 JSON
- ]);
- // 执行请求并获取响应
- $response = curl_exec($ch);
- // 检查是否有错误
- if (strpos($response, "code") !== false) {
- $response = json_decode($response);
- echo '{"code":'.$response ->code.',"msg":"cURL 请求失败: 请检查参数。","data":null}';
- exit;
- } else {
- // 解析 JSON 响应
- $response = json_decode($response, true);
- $response["code"] = 200;
- $response = json_encode($response, JSON_UNESCAPED_UNICODE);
- return $response; // 输出返回数据(prompt, vector, nearest)
- }
- // 关闭 cURL 资源
- curl_close($ch);
- }
-
- public function MCPData(){
- $input = [ [
- "content" => "你好",
- "role" => "user"
- ],
- [
- "content" => "你好!我是EMOON AI助手,有什么可以帮助你的吗?",
- "role" => "assistant"
- ],
- [
- "content" => "查询2025年6月1日到2025年6月2的医院数据 并计算这三天外科的平均住院人数是多少?",
- "role" => "user"
- ],
- ];
- $kid = "";
- $RAGdata = [
- "username" => "test",
- "password" => "test123"
- ];
- // 调用时只需传递非 Content-Type/Accept 的 Header
- $headers = [
- 'Cache-Control: no-cache',
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- ];
- $urlRAG = "http://192.168.1.8:6039/auth/login"; // 替换为实际 URL
-
- $id = curlPostRAG($urlRAG, $RAGdata, $headers);
-
- $token = $id; // 默认启用 JSON 模式
- $token = json_decode($token);
- $token = stdClassObjToArray($token);
- $token = $token['data']['token'];
- $url = "http://192.168.1.8:6039/chat/send"; // 替换成实际接口地址
- $data = [
- "messages" => $input,
- "model" => "qwen3-8B", //X
- "temperature" => 0.5,
- "top_p" => 1,
- "presence_penalty" => 0,
- "frequency_penalty" => 0,
- "kid" => $kid,
- "chat_type" => 0,
- "appId" => "",
- "stream" => true
- ];
-
- // 初始化 cURL
- $ch = curl_init();
- // 设置 cURL 选项
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据
- curl_setopt($ch, CURLOPT_POST, true); // 使用 POST 方法
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 发送 JSON 数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- "Authorization: Bearer " . $token,
- "Content-Type: application/json" // 声明请求体是 JSON
- ]);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
- // 执行请求并获取响应
- $response = curl_exec($ch);
-
- $lines = explode("\n", $response);
- $output = '';
-
- foreach ($lines as $line) {
- if (strpos($line, 'event:chat_completion') !== false) {
- // 提取data部分
- $content = str_replace('event:chat_completion data:', '', $line);
- $output .= trim($content);
- } elseif (trim($line) === '[DONE]') {
- // 处理结束标志
- $output .= "\n[传输结束]";
- }
- }
-
- // 现在$output包含所有提取的内容
- echo $output;
- // 关闭 cURL 资源
- curl_close($ch);
- }
-
- public function handleChat() {
- // 关闭所有缓冲,强制流式输出
- @ini_set('output_buffering', 'off');
- @ini_set('zlib.output_compression', false);
- while (ob_get_level() > 0) {
- ob_end_flush();
- }
- ob_implicit_flush(true);
-
- // 设置流式响应头
- header('Content-Type: text/event-stream; charset=utf-8');
- header('Cache-Control: no-cache');
- header('X-Accel-Buffering: no'); // 对 Nginx 有效,关闭缓冲
-
-
- $requestBody = file_get_contents('php://input');
- $headers = getallheaders();
- $authorizationHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';
-
- $input = [ [
- "content" => "你好",
- "role" => "user"
- ],
- [
- "content" => "你好!我是EMOON AI助手,有什么可以帮助你的吗?",
- "role" => "assistant"
- ],
- [
- "content" => "查询2025年6月1日到2025年6月2的医院数据 并计算这三天外科的平均住院人数是多少?",
- "role" => "user"
- ],
- ];
- $kid = "";
- $RAGdata = [
- "username" => "test",
- "password" => "test123"
- ];
- // 调用时只需传递非 Content-Type/Accept 的 Header
- $headers = [
- 'Cache-Control: no-cache',
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- ];
- $urlRAG = "http://192.168.1.8:6039/auth/login"; // 替换为实际 URL
-
- $id = curlPostRAG($urlRAG, $RAGdata, $headers);
-
- $token = $id; // 默认启用 JSON 模式
- $token = json_decode($token);
- $token = stdClassObjToArray($token);
- $token = $token['data']['token'];
- $url = "http://192.168.1.8:6039/chat/send"; // 替换成实际接口地址
- $data = [
- "messages" => $input,
- "model" => "qwen3-32B", //X
- "temperature" => 0.5,
- "top_p" => 1,
- "presence_penalty" => 0,
- "frequency_penalty" => 0,
- "kid" => $kid,
- "chat_type" => 0,
- "appId" => "",
- "stream" => true
- ];
-
- // 初始化 cURL
- $ch = curl_init();
- // 设置 cURL 选项
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 返回响应数据
- curl_setopt($ch, CURLOPT_POST, true); // 使用 POST 方法
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 发送 JSON 数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- "Authorization: Bearer " . $token,
- "Content-Type: application/json" // 声明请求体是 JSON
- ]);
-
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($url, $data) {
- echo $data;
- @ob_flush();
- @flush();
- return strlen($data);
- });
- $res = curl_exec($ch);
- curl_close($ch);
-
- }
-
- // public function MCPData() {
- // // 1. 强制设置SSE头并关闭缓冲
- // header('Content-Type: text/event-stream');
- // header('Cache-Control: no-cache');
- // ob_end_flush();
-
- // // 2. 模拟流式输出
- // for ($i = 1; $i <= 5; $i++) {
- // echo "event: test\n";
- // echo "data: " . json_encode(['count' => $i, 'time' => date('H:i:s')]) . "\n\n";
- // ob_flush();
- // flush();
- // sleep(1); // 模拟延迟
- // }
-
- // // 3. 结束标记
- // echo "event: end\n";
- // echo "data: {\"status\": \"complete\"}\n\n";
- // ob_flush();
- // flush();
- // }
- //生成随机key
- public function getKey() {
- $count = request() -> param('count');
- $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- $randomString = '';
- for ($i = 0; $i < $count; $i++) {
- $index = rand(0, strlen($characters) - 1);
- $randomString .= $characters[$index];
- }
- return $randomString;
- }
-
- //创建一个测试用例
- public function demo(){
- dump('-----------------------------');
- dump('【参数处理对照DEMO】');
- $information['model'] = 'emoon-E1-13B';
- $information['network'] = '1';
- $messages = [
- [
- 'role' => 'user',
- 'content' => "What is the highest mountain in the world?"
- ],
- [
- 'role' => 'assistant',
- 'content' => 'The highest mountain in the world is Mount Everest.'
- ],
- [
- 'role' => 'user',
- 'content' => 'What is the second?'
- ]
- ];
- $information['input'] = $messages;
- dump('-----------------------------');
- dump('1.数组');
- dump($information);
- //从后端生成是这种格式
- $data = json_encode($information, JSON_UNESCAPED_UNICODE);
- //从前端直接取值是这种格式
- //$data = '{"model":"emoon-E1-13B","network":"1","input":"[{\"role\":\"assistant\",\"content\":\"你好,我是医疗大语言模型「EMOON E1」,请问有什么可以帮您?\"},{\"role\":\"user\",\"content\":\"请问你是什么模型?\"},{\"role\":\"assistant\",\"content\":\"您好!我是EMOON E1 13B模型,一个专注于医疗领域的大语言模型。我由回车网络(EnterLO)训练研发,专门设计来提供医疗专业知识的解读和分析。如果您有任何医疗相关的问题或需要专业建议,我会尽力提供准确和有用的信息。请问有什么具体的医疗问题我可以帮您解答吗?\"},{\"role\":\"user\",\"content\":\"常见的脑科疾病以及对应的预防办法有哪些?\"}]"}';
- dump('-----------------------------');
- dump('2.数组转 json');
- dump($data);
-
- $data = base64_encode($data);
- dump('-----------------------------');
- dump('3.将 json 转换为 base64');
- dump($data);
-
- $config = [
- 'mode' => 'cbc',
- 'key' => 'VKc17yt2QiNZO8Ci', // 16 字节二进制密钥
- 'iv' => '1234567891478523', // 16 字节二进制 IV
- 'hash' => false
- ];
- dump('-----------------------------');
- dump('4.构建 sm4 参数,参数为:');
- dump($config);
-
- $sm4 = new EvitSM4Encryption($config);
- $encryptedBinary = $sm4->encrypt($data);
- dump('-----------------------------');
- dump('5.将 base64 进行 sm4 加密,此时为二进制文件');
- dump($encryptedBinary);
-
- $encryptedBase64 = base64_encode($encryptedBinary);
- dump('-----------------------------');
- dump('6.将二进制 转换为 Base64');
- dump($encryptedBase64);
-
- $modifiedData['encryptedBase64'] = $encryptedBase64;
- $modifiedData['smIV'] = '1234567891478523';
- $modifiedData['publicKey'] = 'tHJZp9mJQPJ4CJAu19F6vhIVa1cyZhP8';
- dump('-----------------------------');
- dump('7.构造最终的请求体数组');
- dump($modifiedData);
-
- $modifiedData = json_encode($modifiedData,JSON_UNESCAPED_UNICODE);
- dump('-----------------------------');
- dump('8.将请求体数组转换为 json');
- dump($modifiedData);
-
- $modifiedData = base64_encode($modifiedData);
- dump('-----------------------------');
- dump('9.将请求体 json 转换为 Base64');
- dump($modifiedData);
-
- $modifiedData = strtr($modifiedData, '+/', '-_');
- dump('-----------------------------');
- dump('10.// 将 + 替换为 -,/ 替换为 _');
- dump($modifiedData);
-
- dump('-----------------------------');
- dump('END.完成构建,将该字符串请求 https://open.emoon.com/apiSSE.php?information=XXXX');
- dump('-----------------------------');
- exit;
- }
-
- //sm4加密
- public function password() {
- $config = [
- 'mode' => 'cbc',
- 'key' => 'jdujuujhjuiki987', // 16 字节二进制密钥
- 'iv' => 'jdujuujhjuiki988', // 16 字节二进制 IV
- 'hash' => false
- ];
- $sm4 = new EvitSM4Encryption($config);
- // 加密
- $plaintext = 'nihao';
- $encryptedBinary = $sm4->encrypt($plaintext);
- // 将二进制结果转换为 Base64
- $encryptedBase64 = base64_encode($encryptedBinary);
- var_dump("Cipher text (Base64): " . $encryptedBase64);
- }
-
- //sm4解密
- public function unpassword(){
- $config = [
- 'mode' => 'cbc',
- 'key' => 'jdujuujhjuiki987', // 16 字节二进制密钥
- 'iv' => 'jdujuujhjuiki988', // 16 字节二进制 IV
- 'hash' => false
- ];
- $sm4 = new EvitSM4Encryption($config);
- // Decrypt
- $pass = 'fI7Cs/lAmFzG7EIuMKAyPQ==';
- $pass = base64_decode($pass);
- $decrypted = $sm4->decrypt($pass);
- var_dump("Plain text(Base64): " . $decrypted);
- }
- }
|