|
|
|
package com.zhonglai.luhui.openai.controller;
|
|
|
|
|
|
|
|
import cn.hutool.http.HttpUtil;
|
|
|
|
import com.alibaba.fastjson.JSON;
|
|
|
|
import com.alibaba.fastjson.JSONObject;
|
|
|
|
import com.ruoyi.common.core.controller.BaseController;
|
|
|
|
import com.ruoyi.common.core.domain.AjaxResult;
|
|
...
|
...
|
@@ -20,12 +21,14 @@ import com.theokanning.openai.Usage; |
|
|
|
import com.theokanning.openai.completion.CompletionChoice;
|
|
|
|
import com.theokanning.openai.completion.CompletionResult;
|
|
|
|
import com.zhonglai.luhui.openai.dto.*;
|
|
|
|
import com.zhonglai.luhui.openai.service.VipServiceImpl;
|
|
|
|
import com.zhonglai.luhui.openai.utils.OpenAiUtils;
|
|
|
|
import com.zhonglai.luhui.openai.utils.SysConfigKeyType;
|
|
|
|
import io.swagger.annotations.Api;
|
|
|
|
import io.swagger.annotations.ApiOperation;
|
|
|
|
import okhttp3.Request;
|
|
|
|
import okhttp3.Response;
|
|
|
|
import org.apache.catalina.Session;
|
|
|
|
import org.apache.commons.io.input.ReaderInputStream;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
...
|
...
|
@@ -38,10 +41,7 @@ import java.io.ByteArrayOutputStream; |
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.InputStream;
|
|
|
|
import java.math.BigDecimal;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Map;
|
|
|
|
import java.util.Optional;
|
|
|
|
import java.util.*;
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
@Api(tags = "chatGPT接口")
|
|
...
|
...
|
@@ -51,9 +51,14 @@ public class ChatGPTController extends BaseController { |
|
|
|
@Autowired
|
|
|
|
private PublicService publicService;
|
|
|
|
|
|
|
|
@ApiOperation("与AI机器进行聊天")
|
|
|
|
@Autowired
|
|
|
|
private VipServiceImpl vipService;
|
|
|
|
|
|
|
|
private static String sessionkey = "CHAT_HISTORY_CONTEXT";//上下文关联存放地址
|
|
|
|
|
|
|
|
@ApiOperation("与AI机器进行聊天(废弃)")
|
|
|
|
@RequestMapping(value = "/aiChatbot",method = RequestMethod.POST)
|
|
|
|
public Message aiChatbot(HttpServletRequest httpServletRequest, @RequestBody String data)
|
|
|
|
public AjaxResult aiChatbot(HttpServletRequest httpServletRequest, @RequestBody String data)
|
|
|
|
{
|
|
|
|
HttpSession session = httpServletRequest.getSession();
|
|
|
|
if(session!=null)
|
|
...
|
...
|
@@ -66,10 +71,10 @@ public class ChatGPTController extends BaseController { |
|
|
|
i+=completionChoice.getText().length();
|
|
|
|
}
|
|
|
|
logger.info("{}请求的流量:{},回复的流量:{}",session.getId(),data.length(),i);
|
|
|
|
return new Message(MessageCode.DEFAULT_SUCCESS_CODE,list);
|
|
|
|
return AjaxResult.success(list);
|
|
|
|
}
|
|
|
|
List<CompletionChoice> list = OpenAiUtils.getAiChatbot(data);
|
|
|
|
return new Message(MessageCode.DEFAULT_SUCCESS_CODE,list);
|
|
|
|
return AjaxResult.success(list);
|
|
|
|
}
|
|
|
|
|
|
|
|
private ChatRoomMessages mapToChatRoomMessages(Map<String,Object> src)
|
|
...
|
...
|
@@ -79,58 +84,80 @@ public class ChatGPTController extends BaseController { |
|
|
|
return chatRoomMessages;
|
|
|
|
}
|
|
|
|
|
|
|
|
@ApiOperation("chatgpt3.5")
|
|
|
|
@ApiOperation(value = "历史记录",notes = "默认获取最新5条记录")
|
|
|
|
@Transactional
|
|
|
|
@RequestMapping(value = "/roomHistory",method = RequestMethod.GET)
|
|
|
|
public AjaxResult roomHistory()
|
|
|
|
{
|
|
|
|
//跟进用户信息生成入口参数
|
|
|
|
OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser();
|
|
|
|
Integer user_id= userInfo.getUserId().intValue();
|
|
|
|
String room_id = String.valueOf(user_id);
|
|
|
|
List<Map<String,Object>> list = publicService.getObjectListBySQL("SELECT * FROM `lk_openai`.`gpt_message` WHERE room_id="+room_id+" AND user_id="+user_id+" order by create_time desc 5");
|
|
|
|
Collections.reverse(list);
|
|
|
|
return AjaxResult.success(list);
|
|
|
|
}
|
|
|
|
|
|
|
|
@ApiOperation(value = "chatgpt3.5",notes = "上下文关联,要实现上下问关联就需要记录整个聊天的提问记录,目前只支持相同session的上下文关联,就是说,如果聊天页面关闭以后再打开,是没有上下文关联的")
|
|
|
|
@Transactional
|
|
|
|
@RequestMapping(value = "/chatgptV3_5",method = RequestMethod.POST)
|
|
|
|
public Message chatgptV3_5(HttpServletRequest httpServletRequest, @RequestBody String data)
|
|
|
|
public AjaxResult chatgptV3_5(HttpServletRequest httpServletRequest,@RequestBody String data)
|
|
|
|
{
|
|
|
|
//跟进用户信息生成入口参数
|
|
|
|
OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser();
|
|
|
|
Integer user_id= userInfo.getUserId().intValue();
|
|
|
|
String room_id = String.valueOf(user_id);
|
|
|
|
|
|
|
|
OpenAiUserInfo openAiUserInfo = (OpenAiUserInfo) userInfo.getUser();
|
|
|
|
if(openAiUserInfo.getFlow_packet_remain()<=0)
|
|
|
|
{
|
|
|
|
return new Message(MessageCode.DEFAULT_FAIL_CODE,"余量不足");
|
|
|
|
}
|
|
|
|
|
|
|
|
List<Map<String,Object>> unitpriceList = publicService.getObjectListBySQL("select `key`,`value` from `lk_openai`.`sys_config` where `key_type`='"+SysConfigKeyType.gpt_3_5_unitprice+"'");
|
|
|
|
BigDecimal openaiUnitprice = new BigDecimal(0);
|
|
|
|
BigDecimal realityUnitprice = new BigDecimal(0);
|
|
|
|
if(null != unitpriceList && unitpriceList.size() !=0)
|
|
|
|
List<CompletionChoiceMessage3_5> rlist = new ArrayList<>();
|
|
|
|
|
|
|
|
//验证余额是否充足
|
|
|
|
if(vipService.isCharging(openAiUserInfo.getVip_level()) && openAiUserInfo.getFlow_packet_remain()<=0)
|
|
|
|
{
|
|
|
|
for(Map<String,Object> map:unitpriceList)
|
|
|
|
{
|
|
|
|
if("openai".equals(map.get("key")))
|
|
|
|
{
|
|
|
|
openaiUnitprice = new BigDecimal(map.get("value").toString());
|
|
|
|
}else if("reality".equals(map.get("key")))
|
|
|
|
{
|
|
|
|
realityUnitprice = new BigDecimal(map.get("value").toString());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
CompletionChoiceMessage3_5 completionChoiceMessage3_5 = new CompletionChoiceMessage3_5();
|
|
|
|
completionChoiceMessage3_5.setRole("assistant");
|
|
|
|
StringBuffer stringBuffer = new StringBuffer();
|
|
|
|
stringBuffer.append("您的余额不足请联系管理员或者点击链接充值:\\n\\n");
|
|
|
|
stringBuffer.append("https://充值链接.com");
|
|
|
|
completionChoiceMessage3_5.setContent(stringBuffer.toString());
|
|
|
|
rlist.add(completionChoiceMessage3_5);
|
|
|
|
|
|
|
|
return AjaxResult.success(rlist);
|
|
|
|
}
|
|
|
|
|
|
|
|
BigDecimal[] bs = vipService.getUnitprice();
|
|
|
|
BigDecimal openaiUnitprice = bs[0];
|
|
|
|
BigDecimal realityUnitprice = bs[1];
|
|
|
|
if(openaiUnitprice.intValue()==0 || realityUnitprice.intValue()==0)
|
|
|
|
{
|
|
|
|
return new Message(MessageCode.DEFAULT_FAIL_CODE,"系统未配置流量单价,请联系管理员");
|
|
|
|
rlist.add(new CompletionChoiceMessage3_5("assistant","系统未配置流量单价,请联系管理员"));
|
|
|
|
return AjaxResult.success(rlist);
|
|
|
|
}
|
|
|
|
|
|
|
|
String room_id = String.valueOf(user_id);
|
|
|
|
logger.info("{}生成聊天会话:",room_id);
|
|
|
|
|
|
|
|
List<Map<String,Object>> list = publicService.getObjectListBySQL("SELECT send_role role,send_content content FROM `lk_openai`.`gpt_message` WHERE room_id='"+room_id+"' AND user_id="+user_id+" order by create_time asc limit 5");
|
|
|
|
|
|
|
|
List<ChatRoomMessages> messageList = Optional.ofNullable(list).orElse(new ArrayList<>()).stream().map(item->mapToChatRoomMessages(item)).collect(Collectors.toList());
|
|
|
|
|
|
|
|
//上下文关联
|
|
|
|
HttpSession session = httpServletRequest.getSession();
|
|
|
|
List<ChatRoomMessages> messageList = Optional.ofNullable((List<Map<String, Object>>) session.getAttribute(sessionkey)).orElse(new ArrayList<>()).stream().map(item->mapToChatRoomMessages(item)).collect(Collectors.toList());
|
|
|
|
ChatRoomMessages chatRoomMessages = new ChatRoomMessages();
|
|
|
|
chatRoomMessages.setRole("user");
|
|
|
|
chatRoomMessages.setContent(data);
|
|
|
|
messageList.add(chatRoomMessages);
|
|
|
|
session.setAttribute(sessionkey,messageList);
|
|
|
|
|
|
|
|
//获取返回参数
|
|
|
|
CompletionResult3_5 completionResult3_5 = sendGPTAi(messageList);
|
|
|
|
CompletionResult3_5 completionResult3_5 = null;
|
|
|
|
if(vipService.isfree(openAiUserInfo.getVip_level()))
|
|
|
|
{
|
|
|
|
completionResult3_5 = sendGPTAi(messageList);
|
|
|
|
}else{
|
|
|
|
completionResult3_5 = sendFreeGPTAi(messageList);
|
|
|
|
}
|
|
|
|
|
|
|
|
Usage usage = completionResult3_5.getUsage();
|
|
|
|
|
|
|
|
List<CompletionChoice3_5> list3_5 = completionResult3_5.getChoices();
|
|
|
|
List<CompletionChoiceMessage3_5> rlist = new ArrayList<>();
|
|
|
|
|
|
|
|
if(null != list3_5 && list3_5.size() !=0 )
|
|
|
|
{
|
|
...
|
...
|
@@ -150,6 +177,7 @@ public class ChatGPTController extends BaseController { |
|
|
|
//统计代币
|
|
|
|
gptMessage.setCompletion_tokens(usage.getCompletionTokens());
|
|
|
|
gptMessage.setPrompt_tokens(usage.getPromptTokens());
|
|
|
|
gptMessage.setTotal_tokens(usage.getTotalTokens());
|
|
|
|
}else{
|
|
|
|
gptMessage.setSend_size(0);
|
|
|
|
}
|
|
...
|
...
|
@@ -183,18 +211,31 @@ public class ChatGPTController extends BaseController { |
|
|
|
UserFlowPacketRemainLog userFlowPacketRemainLog = new UserFlowPacketRemainLog();
|
|
|
|
userFlowPacketRemainLog.setCreate_time(DateUtils.getNowTimeMilly());
|
|
|
|
userFlowPacketRemainLog.setUser_id(openAiUserInfo.getId());
|
|
|
|
userFlowPacketRemainLog.setRoom_id(room_id);
|
|
|
|
userFlowPacketRemainLog.setPrompt_tokens(usage.getPromptTokens());
|
|
|
|
userFlowPacketRemainLog.setCompletion_tokens(usage.getCompletionTokens());
|
|
|
|
userFlowPacketRemainLog.setType(2); //消费
|
|
|
|
|
|
|
|
StringBuffer stringBuffer = new StringBuffer();
|
|
|
|
stringBuffer.append("房间号:");
|
|
|
|
stringBuffer.append(room_id);
|
|
|
|
stringBuffer.append("发送代币:");
|
|
|
|
stringBuffer.append(usage.getPromptTokens());
|
|
|
|
stringBuffer.append("返回代币:");
|
|
|
|
stringBuffer.append(usage.getCompletionTokens());
|
|
|
|
userFlowPacketRemainLog.setDescribe(stringBuffer.toString());
|
|
|
|
userFlowPacketRemainLog.setTotal_tokens(usage.getTotalTokens());
|
|
|
|
|
|
|
|
userFlowPacketRemainLog.setOpenai_money(openaiUnitprice.multiply(new BigDecimal(usage.getTotalTokens())).divide(new BigDecimal(1000),6));
|
|
|
|
userFlowPacketRemainLog.setReality_money(realityUnitprice.multiply(new BigDecimal(usage.getTotalTokens())).divide(new BigDecimal(1000),6));
|
|
|
|
publicService.insertToTable(userFlowPacketRemainLog,"`lk_openai`.`user_flow_packet_remain_log`");
|
|
|
|
}
|
|
|
|
return new Message(MessageCode.DEFAULT_FAIL_CODE,rlist);
|
|
|
|
return AjaxResult.success(rlist);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 付费接口
|
|
|
|
* @param messageList
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
private CompletionResult3_5 sendGPTAi(List<ChatRoomMessages> messageList)
|
|
|
|
{
|
|
|
|
JSONObject jsonObject = new JSONObject();
|
|
...
|
...
|
@@ -205,6 +246,21 @@ public class ChatGPTController extends BaseController { |
|
|
|
return completionResult;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 免费接口
|
|
|
|
* @param messageList
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
private CompletionResult3_5 sendFreeGPTAi(List<ChatRoomMessages> messageList)
|
|
|
|
{
|
|
|
|
JSONObject jsonObject = new JSONObject();
|
|
|
|
jsonObject.put("model","gpt-3.5-turbo-0301");
|
|
|
|
jsonObject.put("messages",messageList);
|
|
|
|
String str = HttpUtil.post("https://free.chatgpt.njlaikun.com/v1/chat/completions",jsonObject.toString());
|
|
|
|
CompletionResult3_5 completionResult = JSONObject.parseObject(str, CompletionResult3_5.class);
|
|
|
|
return completionResult;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static byte[] readInputStream(InputStream inputStream) throws IOException {
|
|
|
|
byte[] buffer = new byte[1024];
|
|
|
|
int len = 0;
|
...
|
...
|
|