Commit 4bbe7675 by cyx

Commit 20230830 Wed

parent 4fe32bc3
package qiwu.xfllmdemo.controller;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import qiwu.xfllmdemo.mapper.DBMapper;
import qiwu.xfllmdemo.pojo.AuditDataDAO;
import qiwu.xfllmdemo.pojo.AuditQueryDAO;
import qiwu.xfllmdemo.pojo.AuditResponseVO;
@Controller
@RequestMapping("/api/audit")
public class AuditController {
@Autowired
private DBMapper dbMapper;
@GetMapping(value = "/getAuditData")
@CrossOrigin // 允许跨域请求
@ResponseBody // 令返回值作为响应体内容
public String getAuditData(@RequestParam("searchText") String searchText,
@RequestParam("auditStatus") String auditStatus,
@RequestParam("pageNum") int pageNum,
@RequestParam("pageSize") int pageSize,
@RequestParam("sortMethod") String sortMethod,
HttpServletResponse response) {
// TODO 1. 参数处理、请求
int offset = (pageNum - 1) * pageSize;
Short as;
try {
as = Short.valueOf(auditStatus);
} catch (NumberFormatException e) {
as = null;
}
AuditQueryDAO aqDAO = new AuditQueryDAO(searchText, as, offset, pageSize, sortMethod);
// Test
System.out.println("aqDAO: " + aqDAO);
// TODO 2. 构造回复
AuditResponseVO arVO = new AuditResponseVO();
try {
arVO.data.pageNum = pageNum;
arVO.data.pageSize = pageSize;
arVO.data.total = dbMapper.getAuditDataTotal(aqDAO);
arVO.data.records = dbMapper.getAuditData(aqDAO);
} catch (Exception e) { // Failing
e.printStackTrace();
arVO.code = 0;
arVO.msg = "失败";
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
return JSON.toJSONString(arVO);
}
/**
* 更新一条模型回复的审核状态(一并提交人工修改)
* @param adDAO 前端需传入:该条回复的optId、新的auditStatus;如有人工修改则传入新的reply,否则reply留null
* @return {"code": , "msg": }
*/
@PutMapping(value = "/putAuditData")
@CrossOrigin // 允许跨域请求
@ResponseBody // 令返回值作为响应体内容
public String putAuditData(@RequestBody AuditDataDAO adDAO, HttpServletResponse response) {
try {
Integer i = dbMapper.putAuditData(adDAO); // TODO Returning i?
response.setStatus(HttpServletResponse.SC_OK);
return "{\"code\": 1, \"msg\": \"成功\"}";
} catch (Exception e) {
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return "{\"code\": 0, \"msg\": \"失败\"}";
}
}
}
......@@ -10,26 +10,29 @@ import qiwu.xfllmdemo.pojo.*;
import qiwu.xfllmdemo.service.LLMService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
@Controller
// @RestMapping
@RequestMapping("/pregen")
@RequestMapping("/api/pregen")
public class PreGenerateController {
@Autowired
private DBMapper dbMapper;
@Autowired
private LLMService llmService = new LLMService();
String uploadDir = "/home/cyx/uploadedFile"; // TODO 存储文件的目录
String uploadDir = "/home/cyx/uploadedFile"; // TODO 存储客户端传来文件的目录
String fileName = "uploadedUserWords.txt"; // file.getOriginalFilename(); // TODO 存储到服务器上的文件名称
File sourceFile; // 上传的文件存储路径,构造方法中构建
PreGenerateController() {
sourceFile = new File(uploadDir + File.separator + fileName);
}
/**
* 客户端上传文件到服务器
* @return "uploadFile OK"
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@CrossOrigin // 允许跨域请求
@ResponseBody // 令返回值作为响应体内容
......@@ -60,9 +63,12 @@ public class PreGenerateController {
return "uploadFile OK";
}
/**
* 读取客户端传来的文件,为选定的角色生成每条用户话语对应的回答
*/
@PostMapping(value = "/generate")
@CrossOrigin
public void generate(@RequestBody String requirement, HttpServletResponse response) throws Exception {
public void generate(@RequestBody String requirement, HttpServletResponse response) {
try {
// Test
System.out.println("generate()");
......@@ -73,20 +79,23 @@ public class PreGenerateController {
StringBuilder u = new StringBuilder(sc.nextLine());
// TODO 1.1 处理csv的逗号
while (u.charAt(u.length() - 1) == ',') {
u.deleteCharAt(u.charAt(u.length() - 1));
u.deleteCharAt(u.length() - 1);
}
// Test
System.out.println(u);
// System.out.println(u);
toGenList.add(u.toString());
}
// TODO 2. List逐条请求模型,获得回复
// TODO 2.1 取得DB中意图ID值
int nowIntentionID = dbMapper.getMaxIntentionID();
// Test
System.out.println("nowIntentionID: " + nowIntentionID);
if (nowIntentionID <= 0) {
// org.apache.ibatis.binding.BindingException: Mapper method 'qiwu.xfllmdemo.mapper.DBMapper.getMaxIntentionID' attempted to return null from a method with a primitive return type (int).
Integer nowIntentionID = dbMapper.getMaxIntentionID();
if (nowIntentionID == null) {
// Test
System.out.println("nowIntentionID == null");
nowIntentionID = 1;
}
// Test
System.out.println("nowIntentionID: " + nowIntentionID);
// TODO 2.2 请求模型
List<IntentionDAO> iList = new LinkedList<>();
List<OptDAO> oList = new LinkedList<>();
......@@ -95,12 +104,14 @@ public class PreGenerateController {
System.out.println("thisUUID: " + thisUUID);
// TODO 2.2.1 告知模型生成要求
// Test
System.out.println("requirement: " + requirement);
llmService.query(new LLMServiceRequestVO(thisUUID, requirement));
System.out.println("requirement: \n" + requirement);
String reqRes = llmService.query(new LLMQueryVO(thisUUID, requirement), 1, true).answer;
System.out.println("reqRes: " + reqRes);
// TODO 2.2.2 用户话语逐条请求
for (String thisSentence : toGenList) {
LLMServiceResponseVO llmResponse = llmService.query(new LLMServiceRequestVO(thisUUID, thisSentence));
LLMAnswerVO llmResponse = llmService.query(new LLMQueryVO(thisUUID, thisSentence), 1, false);
// Test
System.out.print("res" + nowIntentionID + ": ");
System.out.println(new DialogueVO(thisSentence, nowIntentionID, llmResponse.answer));
iList.add(new IntentionDAO(thisSentence, nowIntentionID));
oList.add(new OptDAO(nowIntentionID, llmResponse.answer));
......@@ -122,4 +133,44 @@ public class PreGenerateController {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
/**
* 重新生成单条用户话语的回复
* @param inDAO 前端需传入:userWords、optId、roleId
*/
@PostMapping(value = "/generateOne")
@CrossOrigin
@ResponseBody
public String generateOne(@RequestBody AuditDataDAO inDAO, HttpServletResponse response) {
try {
// TODO 1. 查DB,取得角色对应的人物设定(role_info)->模型生成要求
// Test
System.out.println(inDAO);
RolesDAO ridDAO = new RolesDAO();
ridDAO.setId(inDAO.getRoleId());
RolesDAO roleDAO = dbMapper.getRoleById(ridDAO);
System.out.println("roleDAO: " + roleDAO);
// TODO 2. 请求模型
UUID thisUUID = UUID.randomUUID(); // 每一次生成,与模型使用一个对话
llmService.query(new LLMQueryVO(thisUUID, roleDAO.getRoleInfo()), 1, true);
LLMAnswerVO reqRes = llmService.query(new LLMQueryVO(thisUUID, inDAO.getUserWords()), 1, false);
// Test
System.out.println(reqRes.answer);
// TODO 3. 根据回答及optId构造AuditDataDAO,将回复更新到DB
AuditDataDAO insertDAO = new AuditDataDAO();
insertDAO.setOptId(inDAO.getOptId());
insertDAO.setAuditStatus((short) 0); // 自动生成的回复默认不通过
insertDAO.setReply(reqRes.answer);
dbMapper.putAuditData(insertDAO);
// Test
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader("message", "Success");
return "{\"code\": 1}";
} catch (Exception e) {
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setHeader("message", "Error");
return "{\"code\": 0}";
}
}
}
......@@ -5,8 +5,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import qiwu.xfllmdemo.pojo.LLMServiceRequestVO;
import qiwu.xfllmdemo.pojo.LLMServiceResponseVO;
import qiwu.xfllmdemo.pojo.LLMQueryVO;
import qiwu.xfllmdemo.pojo.LLMAnswerVO;
import qiwu.xfllmdemo.pojo.QueryRequestVO;
import qiwu.xfllmdemo.pojo.QueryResponseVO;
import qiwu.xfllmdemo.service.LLMService;
......@@ -17,8 +17,8 @@ public class QueryController {
@Autowired
LLMService llmService = new LLMService();
@RequestMapping(value = "/queryModel", method = RequestMethod.POST, headers = "Accept=application/json")
public QueryResponseVO queryModel(@RequestBody QueryRequestVO queryRequestVO) {
LLMServiceResponseVO res = llmService.query(new LLMServiceRequestVO(queryRequestVO));
public QueryResponseVO queryModel(@RequestBody QueryRequestVO queryRequestVO) throws Exception {
LLMAnswerVO res = llmService.query(new LLMQueryVO(queryRequestVO), 1, true);
QueryResponseVO repVO = new QueryResponseVO(res);
return repVO;
}
......
package qiwu.xfllmdemo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import qiwu.xfllmdemo.pojo.DialogueVO;
import qiwu.xfllmdemo.pojo.IntentionDAO;
import qiwu.xfllmdemo.pojo.OptDAO;
import qiwu.xfllmdemo.pojo.*;
import java.util.List;
@Component
@Mapper
public interface DBMapper {
int getMaxIntentionID();
int insertIntoIntention(List<IntentionDAO> intentionDAOList);
int insertIntoOpt(List<OptDAO> optDAOList);
// /pregen
/**
* 获得当前最大的意图ID
*/
Integer getMaxIntentionID();
Integer insertIntoIntention(List<IntentionDAO> intentionDAOList);
Integer insertIntoOpt(List<OptDAO> optDAOList);
List<DialogueVO> getReply(String user_words);
// /audit
/**
* 根据审核页面的查询条件取得对应的结果(经过LIMIT和OFFSET)
*/
List<AuditDataDAO> getAuditData(AuditQueryDAO auditQueryDAO);
/**
* 根据审核页面的查询条件取得对应的结果总数(未经过LIMIT和OFFSET)
*/
Integer getAuditDataTotal(AuditQueryDAO auditQueryDAO);
Integer putAuditData(AuditDataDAO auditDataDAO);
RolesDAO getRoleById(RolesDAO rolesDAO);
}
package qiwu.xfllmdemo.pojo;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 审核页面查询响应体中的每条数据 信息结构
*/
public class AuditDataDAO {
@JSONField
String userWords;
@JSONField
int optId;
@JSONField
int intentionId;
@JSONField
int roleId;
@JSONField
String roleName;
@JSONField
String reply;
@JSONField
short auditStatus;
public int getOptId() {
return optId;
}
public void setOptId(int optId) {
this.optId = optId;
}
public String getUserWords() {
return userWords;
}
public void setUserWords(String userWords) {
this.userWords = userWords;
}
public int getIntentionId() {
return intentionId;
}
public void setIntentionId(int intentionId) {
this.intentionId = intentionId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public short getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(short auditStatus) {
this.auditStatus = auditStatus;
}
@Override
public String toString() {
return "AuditBO{" +
"optId=" + optId +
", userWords='" + userWords + '\'' +
", intentionId=" + intentionId +
", roleId=" + roleId +
", roleName='" + roleName + '\'' +
", reply='" + reply + '\'' +
", auditStatus=" + auditStatus +
'}';
}
}
package qiwu.xfllmdemo.pojo;
/**
* 审核页面查询请求体 信息结构
*/
public class AuditQueryDAO {
String searchText;
Short auditStatus;
int offset;
int pageSize;
String sortMethod;
public AuditQueryDAO() {
}
public AuditQueryDAO(String searchText, Short auditStatus, int offset, int pageSize, String sortMethod) {
this.searchText = searchText;
this.auditStatus = auditStatus;
this.offset = offset;
this.pageSize = pageSize;
this.sortMethod = sortMethod;
}
public String getSearchText() {
return searchText;
}
public void setSearchText(String searchText) {
this.searchText = searchText;
}
public Short getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(Short auditStatus) {
this.auditStatus = auditStatus;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getSortMethod() {
return sortMethod;
}
public void setSortMethod(String sortMethod) {
this.sortMethod = sortMethod;
}
@Override
public String toString() {
return "AuditQueryDAO{" +
"searchText='" + searchText + '\'' +
", auditStatus='" + auditStatus + '\'' +
", pageNum='" + offset + '\'' +
", pageSize='" + pageSize + '\'' +
", sortMethod='" + sortMethod + '\'' +
'}';
}
}
package qiwu.xfllmdemo.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AuditResponseVO {
@JSONField
public int code = 1;
@JSONField
public String msg = "成功";
@JSONField
public Data data = new Data();
public static class Data {
@JSONField
public int pages;
@JSONField
public int pageNum;
@JSONField
public int pageSize;
@JSONField
public int total;
@JSONField
public List<AuditDataDAO> records;
}
}
package qiwu.xfllmdemo.pojo;
/**
* 当前仅用于测试时输出结果
*/
public class DialogueVO {
String user_words;
int intention_id;
......@@ -10,10 +13,18 @@ public class DialogueVO {
this.user_words = user_words;
this.intention_id = intention_id;
}
public DialogueVO(String user_words, int intention_id, String reply) {
this.user_words = user_words;
this.intention_id = intention_id;
this.reply = reply;
}
@Override
public String toString() {
return "DialogueVO{" +
"user_words='" + user_words + '\'' +
", intention_id=" + intention_id +
", \nreply='" + reply + '\'' +
'}';
}
}
package qiwu.xfllmdemo.pojo;
/**
* intention表 信息结构
*/
public class IntentionDAO {
int id;
String user_words;
int intention_id;
String userWords;
int intentionId;
int roleId;
public IntentionDAO(String user_words, int intention_id) {
this.user_words = user_words;
this.intention_id = intention_id;
public IntentionDAO(String userWords, int intentionId) {
this.userWords = userWords;
this.intentionId = intentionId;
}
public int getId() {
......@@ -18,28 +22,37 @@ public class IntentionDAO {
this.id = id;
}
public String getUser_words() {
return user_words;
public String getUserWords() {
return userWords;
}
public void setUser_words(String user_words) {
this.user_words = user_words;
public void setUserWords(String userWords) {
this.userWords = userWords;
}
public int getIntention_id() {
return intention_id;
public int getIntentionId() {
return intentionId;
}
public void setIntention_id(int intention_id) {
this.intention_id = intention_id;
public void setIntentionId(int intentionId) {
this.intentionId = intentionId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "intentionTableDAO{" +
return "IntentionDAO{" +
"id=" + id +
", user_words='" + user_words + '\'' +
", intention_id=" + intention_id +
", userWords='" + userWords + '\'' +
", intentionId=" + intentionId +
", roleId=" + roleId +
'}';
}
}
......@@ -2,16 +2,16 @@ package qiwu.xfllmdemo.pojo;
import java.util.UUID;
public class LLMServiceResponseVO {
public class LLMAnswerVO {
public UUID userID;
public String answer;
public LLMServiceResponseVO() {
public LLMAnswerVO() {
}
public LLMServiceResponseVO(UUID userID, String answer) {
public LLMAnswerVO(UUID userID, String answer) {
this.userID = userID;
this.answer = answer;
}
public LLMServiceResponseVO(QueryResponseVO queryResponseVO) {
public LLMAnswerVO(QueryResponseVO queryResponseVO) {
this.userID = queryResponseVO.userID;
this.answer = queryResponseVO.answer;
}
......
......@@ -2,16 +2,16 @@ package qiwu.xfllmdemo.pojo;
import java.util.UUID;
public class LLMServiceRequestVO {
public class LLMQueryVO {
public UUID userID;
public String question;
public LLMServiceRequestVO() {
public LLMQueryVO() {
}
public LLMServiceRequestVO(UUID userID, String question) {
public LLMQueryVO(UUID userID, String question) {
this.userID = userID;
this.question = question;
}
public LLMServiceRequestVO(QueryRequestVO queryRequestVO) {
public LLMQueryVO(QueryRequestVO queryRequestVO) {
this.userID = queryRequestVO.userID;
this.question = queryRequestVO.question;
}
......
......@@ -45,11 +45,11 @@ public class LLMRequestVO {
@Data
public static class Chat {
/**
* 指定请求的模型版本,general:V1.5,generalv2:V2 - 非必须,取值为[general,generalv2]
* 指定请求的模型版本,general:V1.5,generalv2:V2 - 必须,取值为[general,generalv2]
*/
@JSONField
// @Builder.Default
public String domain = "general";
public String domain;
/**
* 核采样阈值,用于决定结果随机性。取值越高随机性越强,即相同的问题得到的不同答案的可能性越高 - 非必须,取值为[0,1],默认0.5
*/
......
package qiwu.xfllmdemo.pojo;
/**
* opt表 信息结构
*/
public class OptDAO {
int id;
int intention_id;
int intentionId;
String reply;
boolean audit_status = false;
/**
* 0未审核,1审核通过,2审核不通过
*/
short auditStatus = 0;
int roleId;
public OptDAO(int intention_id, String reply) {
this.intention_id = intention_id;
public OptDAO(int intentionId, String reply) {
this.intentionId = intentionId;
this.reply = reply;
}
......@@ -19,12 +26,12 @@ public class OptDAO {
this.id = id;
}
public int getIntention_id() {
return intention_id;
public int getIntentionId() {
return intentionId;
}
public void setIntention_id(int intention_id) {
this.intention_id = intention_id;
public void setIntentionId(int intentionId) {
this.intentionId = intentionId;
}
public String getReply() {
......@@ -35,21 +42,30 @@ public class OptDAO {
this.reply = reply;
}
public boolean isAudit_status() {
return audit_status;
public short getAuditStatus() {
return auditStatus;
}
public void setAudit_status(boolean audit_status) {
this.audit_status = audit_status;
public void setAuditStatus(short auditStatus) {
this.auditStatus = auditStatus;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "optTableDAO{" +
return "OptDAO{" +
"id=" + id +
", intention_id=" + intention_id +
", intentionId=" + intentionId +
", reply='" + reply + '\'' +
", audit_status=" + audit_status +
", auditStatus=" + auditStatus +
", roleId=" + roleId +
'}';
}
}
......@@ -11,8 +11,8 @@ public class QueryRequestVO {
this.userID = userID;
this.question = question;
}
public QueryRequestVO(LLMServiceRequestVO llmServiceRequestVO) {
this.userID = llmServiceRequestVO.userID;
this.question = llmServiceRequestVO.question;
public QueryRequestVO(LLMQueryVO llmQueryVO) {
this.userID = llmQueryVO.userID;
this.question = llmQueryVO.question;
}
}
......@@ -11,8 +11,8 @@ public class QueryResponseVO {
this.userID = userID;
this.answer = answer;
}
public QueryResponseVO(LLMServiceResponseVO llmServiceResponseVO) {
this.userID = llmServiceResponseVO.userID;
this.answer = llmServiceResponseVO.answer;
public QueryResponseVO(LLMAnswerVO llmAnswerVO) {
this.userID = llmAnswerVO.userID;
this.answer = llmAnswerVO.answer;
}
}
package qiwu.xfllmdemo.pojo;
/**
* roles表 信息结构
*/
public class RolesDAO {
int id;
String roleName;
String roleInfo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleInfo() {
return roleInfo;
}
public void setRoleInfo(String roleInfo) {
this.roleInfo = roleInfo;
}
@Override
public String toString() {
return "RoleDAO{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleInfo='" + roleInfo + '\'' +
'}';
}
}
......@@ -7,39 +7,43 @@ import java.text.SimpleDateFormat;
import java.util.*;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import qiwu.xfllmdemo.pojo.LLMAnswerVO;
import qiwu.xfllmdemo.pojo.LLMRequestVO;
import qiwu.xfllmdemo.pojo.LLMRequestVO.Payload.Message;
import qiwu.xfllmdemo.pojo.LLMResponseVO;
import qiwu.xfllmdemo.pojo.LLMResponseVO.Payload.Choices;
import qiwu.xfllmdemo.pojo.LLMServiceRequestVO;
import qiwu.xfllmdemo.pojo.LLMServiceResponseVO;
import qiwu.xfllmdemo.pojo.LLMQueryVO;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* 向模型发起一次请求,返回这次请求对应的回答
*/
@Service
public class LLMService {
/**
* 所有用户的对话历史列表,<userID, 历史对话List>
*/
static HashMap<UUID, LinkedList<Message.Text>> chatHistory;
static HashMap<UUID, List<Message.Text>> chatHistory;
// static ArrayList<UUID> userList;
static final String hostUrl = "https://spark-api.xf-yun.com/v1.1/chat"; //ws(s)://spark-api.xf-yun.com/v2.1/chat
static final String appid = "76f57fca";
static final String apiSecret = "ZGFiZDAxMWVkM2I5ZDg0YzJhMzVjMjc0";
static final String apiKey = "cbd03b0dc6862d38b24c5c25ba8b0f02";
static String authURL;
static { // 生成鉴权authURL - 代码块先于构造方法执行
/**
* 生成鉴权authURL - 时间戳偏差需控制在300s范围内,故每次请求都需要调用
*/
static void genAuthURL(int modelVersion) {
try {
URL url = new URL(hostUrl);
URL url;
if (modelVersion == 1) {
url = new URL("https://spark-api.xf-yun.com/v1.1/chat");
} else { // modelVersion == 2
url = new URL("https://spark-api.xf-yun.com/v2.1/chat");
}
// 时间
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
......@@ -72,20 +76,21 @@ public class LLMService {
e.printStackTrace();
}
}
public static final Gson gson = new Gson();
/**
* 用于拼接整个回答串
*/
StringBuffer answerBuffer = new StringBuffer();
public LLMService() {
chatHistory = new HashMap<>();
}
public LLMServiceResponseVO query(LLMServiceRequestVO inVO) {
/**
* 根据对话ID(用户ID)和用户话语发起请求
* @param inVO 本次请求的对话ID(用户ID)和用户话语
* @param modelVersion 要请求的模型版本 1:v1.5,2:v2
* @param addToHistory 请求时是否发送历史对话
* @return 本次请求的对话ID(用户ID)和模型的回复
*/
public LLMAnswerVO query(LLMQueryVO inVO, int modelVersion, boolean addToHistory) throws Exception {
// TODO 1. 根据入参获得用户id和对话历史
LinkedList<Message.Text> thisHistory = chatHistory.get(inVO.userID);
List<Message.Text> thisHistory = chatHistory.get(inVO.userID);
if (thisHistory == null) {
// outVO = UUID.randomUUID().toString().substring(0, 10);
thisHistory = new LinkedList<Message.Text>();
......@@ -94,22 +99,44 @@ public class LLMService {
// TODO 2. 构造模型请求JSON,将问题添加到对话历史
LLMRequestVO toReq = new LLMRequestVO();
toReq.header.app_id = appid;
toReq.header.uid = inVO.userID.toString().substring(0, 20);
if (modelVersion == 1) {
toReq.parameter.chat.domain = "general";
} else if (modelVersion == 2) {
toReq.parameter.chat.domain = "generalv2";
} else {
throw new Exception("modelVersion Error, provided value: " + modelVersion);
}
toReq.parameter.chat.chat_id = inVO.userID.toString(); // 以UUID区分用户
thisHistory.add(new Message.Text("user", inVO.question));
toReq.payload.message.text = thisHistory;
Message.Text thisTimeWords = new Message.Text("user", inVO.question);
// TODO on addToHistory
if (addToHistory) {
thisHistory.add(thisTimeWords);
toReq.payload.message.text = thisHistory;
} else {
List<Message.Text> thisTimeList = new LinkedList<>(thisHistory);
thisTimeList.add(thisTimeWords);
toReq.payload.message.text = thisTimeList;
}
String toReqJSON = JSON.toJSONString(toReq);
// Test
System.out.println("toReqJSON: \n" + toReqJSON + "\n------");
System.out.println("authURL: \n" + authURL + "\n------");
// System.out.println("------\n" + "toReqJSON: \n" + toReqJSON);
// System.out.println("authURL: \n" + authURL + "\n------");
// TODO 3. 发起请求,获得回复,将回复添加到对话历史,返回
genAuthURL(modelVersion); // 时间戳偏差需控制在300s范围内,故每次请求都需要调用
LLMSocket llmSocket = new LLMSocket(authURL, toReqJSON);
String thisAnswer = llmSocket.executeQuery().toString();
thisHistory.add(new Message.Text("assistant", thisAnswer));
LLMServiceResponseVO outVO = new LLMServiceResponseVO(inVO.userID, thisAnswer);
return outVO;
// TODO on addToHistory
if (addToHistory) {
thisHistory.add(new Message.Text("assistant", thisAnswer));
}
return new LLMAnswerVO(inVO.userID, thisAnswer);
}
}
/**
* 向模型发起一次请求,返回这次请求对应的回答
*/
class LLMSocket extends WebSocketListener {
/**
* 请求参数JSON
......@@ -125,6 +152,9 @@ class LLMSocket extends WebSocketListener {
* 关闭WebSocket线程标志
*/
boolean wsCloseFlag = false;
/**
* 用于拼接一次请求的整个回答串
*/
StringBuffer outBuffer = new StringBuffer();
static int threadNum = 0;
......@@ -138,7 +168,6 @@ class LLMSocket extends WebSocketListener {
do {
Thread.sleep(200);
} while (!wsCloseFlag);
} catch (InterruptedException e) {
e.printStackTrace();
}
......@@ -165,6 +194,8 @@ class LLMSocket extends WebSocketListener {
Thread.sleep(200);
} while (!wsCloseFlag);
webSocket.close(1000, "");
// Test
System.out.println("webSocket.close() onMessage() " + threadNum);
} catch (Exception e) {
e.printStackTrace();
}
......@@ -193,9 +224,10 @@ class LLMSocket extends WebSocketListener {
public synchronized void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
// System.out.println(userId + "用来区分是哪个用户的结果" + text);
// Test
System.out.println("onMessage() " + threadNum + ": ");
// System.out.println("onMessage() " + threadNum + ": ");
threadNum++;
System.out.println("LLMResponseJSON: " + text);
// Test
// System.out.println("LLMResponseJSON: " + text);
// TODO 1. 解析返回的JSON,若出错处理
// 使用JSON.parseObject()时注意,传入的class中每个属性的类型必须与JSON字符串中严格相同,否则方法会阻塞且不会有任何异常抛出
LLMResponseVO responseVO = JSON.parseObject(text, LLMResponseVO.class);
......@@ -206,14 +238,14 @@ class LLMSocket extends WebSocketListener {
return;
}
// Test
System.out.println("responseVO: " + responseVO);
// System.out.println("responseVO: " + responseVO);
// TODO 2. 提取其中的回答串
List<Choices.Text> textList = responseVO.payload.choices.text;
// Test
System.out.println("textList.size(): " + textList.size());
// System.out.println("textList.size(): " + textList.size());
// TODO 3. 拼接形成完整回答串 每个Response的test里面只有一个元素
for (Choices.Text temp : textList) {
System.out.println("temp.content: " + temp.content);
// System.out.println("temp.content: " + temp.content);
outBuffer.append(temp.content);
}
if (responseVO.header.status == 2) {
......
......@@ -7,7 +7,7 @@ server:
spring:
datasource:
url: jdbc:mysql://localhost:3306/chitchat?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
username: root
username: chatter
password: 7890-=
driver-class-name: com.mysql.cj.jdbc.Driver
data:
......
......@@ -2,28 +2,78 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="qiwu.xfllmdemo.mapper.DBMapper">
<!-- 返回值:结果的行数 -->
<!-- 预生成部分 -->
<!-- project_name as projectName -->
<select id="getMaxIntentionID" resultType="int">
SELECT max(intention_id) --, project_name as projectName
SELECT max(intention_id)
FROM intention
</select>
<!-- 返回值:成功插入的行数 -->
<!-- 返回值:成功插入的行数? -->
<insert id="insertIntoIntention" parameterType="List">
INSERT INTO intention (user_words, intention_id)
INSERT INTO intention (user_words, intention_id, role_id)
VALUES
<foreach collection="list" index="index" item="item" separator=",">
(#{user_words, jdbcType=VARCHAR}, #{intention_id, jdbcType=INTEGER})
(#{item.userWords, jdbcType=VARCHAR}, #{item.intentionId, jdbcType=INTEGER}, null)
</foreach>
</insert>
<insert id="insertIntoOpt" parameterType="List">
INSERT INTO opt (intention_id, reply, audit_status)
INSERT INTO opt (intention_id, reply, audit_status, role_id)
VALUES
<foreach collection="list" index="index" item="item" separator=",">
(#{intention_id, jdbcType=INTEGER}, #{reply, jdbcType=VARCHAR}, #{audit_status, jdbcType=TINYINT})
(#{item.intentionId, jdbcType=INTEGER}, #{item.reply, jdbcType=VARCHAR},
#{item.auditStatus, jdbcType=TINYINT}, null)
</foreach>
</insert>
<insert id="insertIntoRole" parameterType="RolesDAO">
INSERT INTO opt (role_name, role_info)
VALUES (#{roleName, jdbcType=VARCHAR}, #{roleInfo, jdbcType=VARCHAR})
</insert>
<!-- 审核部分 -->
<select id="getAuditData" parameterType="AuditQueryDAO" resultType="AuditDataDAO">
SELECT intention.user_words as userWords, opt.id as optId, intention.intention_id as intentionId,
roles.id as roleId, roles.role_name as roleName, opt.reply as reply, opt.audit_status as auditStatus
FROM intention JOIN roles ON intention.role_id = roles.id
JOIN opt ON intention.intention_id = opt.intention_id
WHERE (intention.user_words LIKE '%${searchText}%'
OR roles.role_name = #{searchText})
<if test='auditStatus != null'>
AND opt.audit_status = #{auditStatus}
</if>
<if test='sortMethod != ""'> <!-- 按角色ID和意图ID排序 -->
ORDER BY roles.id, intention.intention_id ${sortMethod}
</if>
LIMIT #{pageSize}
OFFSET #{offset}
</select>
<select id="getAuditDataTotal" parameterType="AuditQueryDAO" resultType="Integer">
SELECT COUNT(*)
FROM intention JOIN roles ON intention.role_id = roles.id
JOIN opt ON intention.intention_id = opt.intention_id
WHERE (intention.user_words LIKE '%${searchText}%'
OR roles.role_name = '${searchText}')
<if test='auditStatus != null'>
AND opt.audit_status = #{auditStatus}
</if>
</select>
<update id="putAuditData" parameterType="AuditDataDAO">
UPDATE opt
SET audit_status = #{auditStatus, jdbcType=TINYINT}
<if test='reply != null'>, reply = #{reply, jdbcType=VARCHAR} </if>
WHERE id = #{optId, jdbcType=INTEGER}
</update>
<select id="getRoleById" parameterType="RolesDAO" resultType="RolesDAO">
SELECT id as id, role_name as roleName, role_info as roleInfo
FROM roles
WHERE id = #{id}
</select>
<!-- &lt;!&ndash; &ndash;&gt;-->
<!-- <update id="updateProjectInfoByPrimaryKey" parameterType="ProjectEntity">-->
<!-- UPDATE project_info-->
......
......@@ -2,13 +2,21 @@
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--将下划线映射为驼峰-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<!-- 1.可以为实体类设置别名 -->
<typeAlias type="java.lang.String" alias="String"/>
<typeAlias type="java.lang.Integer" alias="Integer"/>
<typeAlias type="java.util.List" alias="List"/>
<typeAlias type="java.util.Date" alias="Date"/>
<typeAlias type="qiwu.xfllmdemo.pojo.IntentionDAO" alias="IntentionDAO"/>
<typeAlias type="qiwu.xfllmdemo.pojo.OptDAO" alias="OptDAO"/>
<typeAlias type="qiwu.xfllmdemo.pojo.RolesDAO" alias="RolesDAO"/>
<typeAlias type="qiwu.xfllmdemo.pojo.AuditDataDAO" alias="AuditDataDAO"/>
<typeAlias type="qiwu.xfllmdemo.pojo.AuditQueryDAO" alias="AuditQueryDAO"/>
<!-- 2.可以指定一个包名,MyBatis会在包名下搜索每一个 Java Bean -->
<!-- 在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名 -->
<!-- <package name="qiwu.xfllmdemo.pojo"/>-->
......@@ -21,7 +29,7 @@
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/chitchat?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="username" value="chatter"/>
<property name="password" value="7890-="/>
</dataSource>
</environment>
......
......@@ -14,6 +14,7 @@ Omit --global to set the identity only in this repository. unable to auto-detect
如果选择 修正并提交 ,将执行 git config --global core.autocrlf input。
如果选择 按原样提交 ,则不会更改配置值。
Lombok 要求已启用的注解处理 - 已启用的注解处理
Lombok 要求已启用的注解处理 - 启用注解处理
!!!使用JSON.parseObject()时注意,传入的class中每个属性的类型必须与JSON字符串中严格相同,否则会导致方法阻塞且不会有任何异常抛出
......@@ -16,7 +16,7 @@
<button id="uploadButton">上传</button>
<progress id="uploadProgressBar" value="0" max="100"></progress> <br>
<p id="divider1">------------------------------</p> <br>
<textarea id="requirementArea" cols = 30 placeholder="在此输入生成要求,如人物设定等"></textarea>
<textarea id="requirementArea" cols=40 rows=10 placeholder="在此输入生成要求,如人物设定等"></textarea>
<button id="genButton">生成</button> <br>
<p id="genInfo"></p> <br>
<p id="divider2">------------------------------</p> <br>
......
......@@ -23,11 +23,10 @@ export const ALLOWED_TYPE = {
export const CHUNK_SIZE = 64 * 1024;
export const API_URLS = {
UPLOAD_FILE: BASE_URL + '/pregen/upload',
START_GEN: BASE_URL + '/pregen/generate'
UPLOAD_FILE: BASE_URL + '/api/pregen/upload',
START_GEN: BASE_URL + '/api/pregen/generate'
};
// index.js
// 在闭包内部,定义一个立即执行的匿名函数,接受document作为参数
((doc) => {
// 获取页面上的一些元素
......@@ -35,11 +34,11 @@ export const API_URLS = {
const fileUploadInput = doc.querySelector('#fileUploadInput'); // 文件上传输入框
const uploadInfo = doc.querySelector('#uploadInfo'); // p,显示上传状态信息
const uploadButton = doc.querySelector('#uploadButton'); // 上传按钮
const requirementArea = doc.querySelector('#requirementArea')
const requirementArea = $('#requirementArea');
const genButton = doc.querySelector('#genButton'); // 开始生成按钮
const genInfo = doc.querySelector('#genInfo'); // p,显示生成状态信息
const genInfo = $('#genInfo'); // p,显示生成状态信息
const downloadButton = doc.querySelector('#downloadButton');
const downloadInfo = doc.querySelector('#downloadInfo');
const downloadInfo = $('#downloadInfo');
let uploadedSize = 0; // 已上传的文件大小,用于控制分块上传
......@@ -50,7 +49,7 @@ export const API_URLS = {
// 绑定事件函数 - 为元素添加事件监听器
uploadButton.addEventListener('click', uploadFile, false); // uploadButton -> uploadFile()
genButton.addEventListener('click', startGen, false); // genButton -> startGen()
downloadButton.addEventListener('click', onDownload, false);
downloadButton.addEventListener('click', onDownload, false); // downloadButton -> onDownload()
}
/**
......@@ -146,7 +145,9 @@ export const API_URLS = {
async function startGen() {
console.log("startGen()");
let requirement = requirementArea.text();
let requirement = requirementArea.val();
// Test
console.log(requirement);
$.ajax({
url: API_URLS["START_GEN"],
type: "POST",
......
GET https://localhost:8081/api/chat/audit/info?searchText=null&auditStatus=null&pageSize=1&pageNum=10&sortMethod=true HTTP/1.1
\ No newline at end of file
package qiwu.xfllmdemo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import qiwu.xfllmdemo.pojo.LLMServiceRequestVO;
import qiwu.xfllmdemo.pojo.LLMServiceResponseVO;
import qiwu.xfllmdemo.mapper.DBMapper;
import qiwu.xfllmdemo.pojo.AuditDataDAO;
import qiwu.xfllmdemo.pojo.AuditQueryDAO;
import qiwu.xfllmdemo.pojo.LLMAnswerVO;
import qiwu.xfllmdemo.pojo.LLMQueryVO;
import qiwu.xfllmdemo.service.LLMService;
import java.util.List;
import java.util.UUID;
@SpringBootTest
// @Controller
class XfLLMDemoApplicationTests {
@Autowired
DBMapper dbMapper;
// @Test
void contextLoads() {
}
@Test
void LLMServiceSingleQuestionTest() {
// @Test
void LLMServiceSingleQuestionTest() throws Exception {
LLMService ls = new LLMService();
String question = "你今日饮咗未?";
LLMServiceRequestVO req = new LLMServiceRequestVO(UUID.fromString("6d7f4741-3bdb-40c8-a2d8-55b505fe6e2a"), question);
LLMServiceResponseVO res = ls.query(req);
LLMQueryVO req = new LLMQueryVO(UUID.fromString("6d7f4741-3bdb-40c8-a2d8-55b505fe6e2a"), question);
LLMAnswerVO res = ls.query(req, 1, true);
System.out.println("------- query() ends -------");
System.out.println("QueryResponseVO: " + res/*.toString()*/);
System.out.println(res.answer);
}
// @Test
void getAuditDataTest() {
AuditQueryDAO aq = new AuditQueryDAO("什", (short) 0, 0, 60, "true");
List<AuditDataDAO> al = dbMapper.getAuditData(aq);
System.out.println("al.size(): " + al.size());
int t = 0;
for (AuditDataDAO i : al) {
// if (t >= 5) break;
System.out.println(i);
t++;
}
Integer yt = dbMapper.getAuditDataTotal(aq);
System.out.println("AuditDataTotal: " + yt);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment