| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103 |
- <?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);
- $url = "http://192.168.10.115:3335/index/roleindex";
- $data["token"]= $token;
- curlPost($url,$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://192.168.10.115: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://192.168.10.115: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://192.168.10.115: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.10.115: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.10.115:6039/rag/schemaNoReRetrieval"; // 替换成实际接口地址
- $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.10.115: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.10.115: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.10.115: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.10.115: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.10.115: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.10.115: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.10.115: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.10.115: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.10.115: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);
- }
-
- //获取对应的回复记录
- public function getreply(){
- $token = request() -> param('token');
- $mapAskInfo['token'] = array('eq',$token);
- $reply = db('askinfo') -> where($mapAskInfo) -> value('reply');
- return $reply;
-
- }
-
- public function role(){
- $askInfoId = request() -> param('askInfoId');
- // $askInfoId = '613802ffbe0b9534fd58606e7f9d8b74';
- $map['token'] = array('eq', $askInfoId);
- $rulename = db('askinfo')->where($map)->value('decrypt');
- $rulename = json_decode($rulename);
- $rulename = stdClassObjToArray($rulename);
- $rulecontent = db('askinfo')->where($map)->value('reply');
- $rulename['reply'] = $rulecontent;
- $rulename = json_encode($rulename,JSON_UNESCAPED_UNICODE);
- return $rulename;
-
-
- }
-
- //检索增强接口
- public function ragDataTEST(){
- $ruleCode = request() -> param('ruleCode');
- $medicalContent = request() -> param('medicalContent');
- $kid = request() -> param('kid');
-
- $RAGdata = [
- "username" => "admin",
- "password" => "admin123"
- ];
- // 调用时只需传递非 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.10.115: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.10.115:6039/system/ruleFinal/fetchMatchingRules"; // 替换成实际接口地址
- $data = [
- "medicalContent" => $medicalContent, // 替换成实际用户输入
- "ruleCode" => $ruleCode, // 替换成实际模型名称
- "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 ragDataMCQC(){
- $ruleCode = request() -> param('ruleCode');
- $medicalContent = request() -> param('medicalContent');
- $kid = request() -> param('kid');
-
- // $ruleCode = 'RYJLZS0002';
- // $medicalContent = 'medicalContent';
- // $kid = 'Rule_Final';
-
- $url = "http://192.168.10.115:6039/system/ruleFinal/fetchMatchingRules"; // 替换成实际接口地址
- $data = [
- "medicalContent" => $medicalContent, // 替换成实际用户输入
- "ruleCode" => $ruleCode, // 替换成实际模型名称
- "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);
- }
- }
|