|
|
|
package com.zhonglai.luhui.openai.controller;
|
|
|
|
|
|
|
|
import cn.hutool.http.HttpUtil;
|
|
|
|
import com.alibaba.fastjson.JSONObject;
|
|
|
|
import com.ruoyi.common.core.controller.BaseController;
|
|
|
|
import com.ruoyi.common.core.domain.AjaxResult;
|
|
|
|
import com.ruoyi.common.core.domain.Message;
|
|
|
|
import com.ruoyi.common.core.domain.MessageCode;
|
|
|
|
import com.ruoyi.common.utils.Arith;
|
|
|
|
import com.ruoyi.common.utils.DateUtils;
|
|
|
|
import com.ruoyi.common.utils.SecurityUtils;
|
|
|
|
import com.ruoyi.common.utils.StringUtils;
|
|
|
|
import com.ruoyi.common.utils.bean.BeanUtils;
|
|
|
|
import com.ruoyi.common.utils.html.HttpUtils;
|
|
|
|
import com.ruoyi.common.utils.http.OkHttpUtils;
|
|
|
|
import com.ruoyi.system.login.dto.OpenAiLoginUser;
|
|
|
|
import com.ruoyi.system.login.dto.OpenAiUserInfo;
|
|
|
|
import com.ruoyi.system.service.PublicService;
|
|
|
|
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.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.commons.io.input.ReaderInputStream;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
|
import javax.servlet.http.HttpSession;
|
|
|
|
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.stream.Collectors;
|
|
|
|
|
|
|
|
@Api(tags = "chatGPT接口")
|
|
|
|
@RestController
|
|
...
|
...
|
@@ -45,4 +72,148 @@ public class ChatGPTController extends BaseController { |
|
|
|
return new Message(MessageCode.DEFAULT_SUCCESS_CODE,list);
|
|
|
|
}
|
|
|
|
|
|
|
|
private ChatRoomMessages mapToChatRoomMessages(Map<String,Object> src)
|
|
|
|
{
|
|
|
|
ChatRoomMessages chatRoomMessages = new ChatRoomMessages();
|
|
|
|
BeanUtils.copyBeanProp(chatRoomMessages,src);
|
|
|
|
return chatRoomMessages;
|
|
|
|
}
|
|
|
|
|
|
|
|
@ApiOperation("chatgpt3.5")
|
|
|
|
@Transactional
|
|
|
|
@RequestMapping(value = "/chatgptV3_5",method = RequestMethod.POST)
|
|
|
|
public Message chatgptV3_5(HttpServletRequest httpServletRequest, @RequestBody String data)
|
|
|
|
{
|
|
|
|
OpenAiLoginUser userInfo = (OpenAiLoginUser) getLoginUser();
|
|
|
|
Integer user_id= userInfo.getUserId().intValue();
|
|
|
|
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)
|
|
|
|
{
|
|
|
|
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());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if(openaiUnitprice.intValue()==0 || realityUnitprice.intValue()==0)
|
|
|
|
{
|
|
|
|
return new Message(MessageCode.DEFAULT_FAIL_CODE,"系统未配置流量单价,请联系管理员");
|
|
|
|
}
|
|
|
|
|
|
|
|
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());
|
|
|
|
|
|
|
|
ChatRoomMessages chatRoomMessages = new ChatRoomMessages();
|
|
|
|
chatRoomMessages.setRole("user");
|
|
|
|
chatRoomMessages.setContent(data);
|
|
|
|
messageList.add(chatRoomMessages);
|
|
|
|
|
|
|
|
//获取返回参数
|
|
|
|
CompletionResult3_5 completionResult3_5 = sendGPTAi(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 )
|
|
|
|
{
|
|
|
|
List<GptMessage> insertGptMessages = new ArrayList<>();
|
|
|
|
int i=0;
|
|
|
|
for (CompletionChoice3_5 completionChoice:list3_5)
|
|
|
|
{
|
|
|
|
GptMessage gptMessage = new GptMessage();
|
|
|
|
gptMessage.setRoom_id(room_id);
|
|
|
|
gptMessage.setUser_id(user_id);
|
|
|
|
gptMessage.setCreate_time(DateUtils.getNowTimeMilly());
|
|
|
|
gptMessage.setSend_role(chatRoomMessages.getRole());
|
|
|
|
gptMessage.setSend_content(chatRoomMessages.getContent());
|
|
|
|
if(insertGptMessages.size()==0) //第一次计数后面不计数
|
|
|
|
{
|
|
|
|
gptMessage.setSend_size(gptMessage.getSend_content().length());
|
|
|
|
//统计代币
|
|
|
|
gptMessage.setCompletion_tokens(usage.getCompletionTokens());
|
|
|
|
gptMessage.setPrompt_tokens(usage.getPromptTokens());
|
|
|
|
}else{
|
|
|
|
gptMessage.setSend_size(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(null != completionChoice.getMessage())
|
|
|
|
{
|
|
|
|
rlist.add(completionChoice.getMessage());
|
|
|
|
|
|
|
|
gptMessage.setMessage_role(completionChoice.getMessage().getRole());
|
|
|
|
gptMessage.setMessage_content(completionChoice.getMessage().getContent());
|
|
|
|
}
|
|
|
|
gptMessage.setMessage_size(0);
|
|
|
|
if(null != gptMessage.getMessage_content())
|
|
|
|
{
|
|
|
|
gptMessage.setMessage_size(gptMessage.getMessage_content().length());
|
|
|
|
}
|
|
|
|
i+=gptMessage.getMessage_content().length();
|
|
|
|
|
|
|
|
insertGptMessages.add(gptMessage);
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.info("{} 请求的流量:{},回复的流量:{}",room_id,messageList.get(messageList.size()-1).getContent().length(),i);
|
|
|
|
|
|
|
|
if(null != insertGptMessages && insertGptMessages.size() !=0 )
|
|
|
|
{
|
|
|
|
publicService.insertAllToTable(insertGptMessages,"`lk_openai`.`gpt_message`");
|
|
|
|
}
|
|
|
|
|
|
|
|
publicService.updateBySql("UPDATE `user_info` SET flow_packet_remain=flow_packet_remain-"+usage.getTotalTokens()+" WHERE id="+openAiUserInfo.getId());
|
|
|
|
|
|
|
|
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.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);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private CompletionResult3_5 sendGPTAi(List<ChatRoomMessages> messageList)
|
|
|
|
{
|
|
|
|
JSONObject jsonObject = new JSONObject();
|
|
|
|
jsonObject.put("model","gpt-3.5-turbo-0301");
|
|
|
|
jsonObject.put("messages",messageList);
|
|
|
|
String str = HttpUtil.post("https://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;
|
|
|
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
|
|
|
while((len = inputStream.read(buffer)) != -1) {
|
|
|
|
bos.write(buffer, 0, len);
|
|
|
|
}
|
|
|
|
bos.close();
|
|
|
|
return bos.toByteArray();
|
|
|
|
}
|
|
|
|
|
|
|
|
} |
...
|
...
|
|