Commit eaf1863d by cyx

Commit 20230818 Fri

parent 3b65af44
......@@ -5,6 +5,7 @@ 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.QueryRequestVO;
import qiwu.xfllmdemo.pojo.QueryResponseVO;
......@@ -17,7 +18,8 @@ public class QueryController {
LLMService llmService = new LLMService();
@RequestMapping(value = "/queryModel", method = RequestMethod.POST, headers = "Accept=application/json")
public QueryResponseVO queryModel(@RequestBody QueryRequestVO queryRequestVO) {
LLMServiceResponseVO res = llmService.query();
LLMServiceResponseVO res = llmService.query(new LLMServiceRequestVO(queryRequestVO));
QueryResponseVO repVO = new QueryResponseVO(res);
return repVO;
}
}
......@@ -6,6 +6,7 @@ import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/**
......@@ -16,86 +17,87 @@ import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
public class LLMRequestVO {
@JSONField(name = "header")
public Header header;
@JSONField
public Header header = new Header();
@Data
public static class Header {
/**
* 应用appid,从开放平台控制台创建的应用中获取
*/
@JSONField(name = "chat_id")
@JSONField
public String app_id;
/**
* 每个用户的id,用于区分不同用户 - 非必须,最大长度32
*/
@JSONField(name = "uid")
@JSONField
public String uid;
}
@JSONField(name = "parameter")
public Parameter parameter;
@JSONField
public Parameter parameter = new Parameter();
@Data
public static class Parameter {
@JSONField(name = "chat")
public Chat chat;
@JSONField
public Chat chat = new Chat();
@Data
public static class Chat {
/**
* 指定请求的模型版本,general:V1.5,generalv2:V2 - 非必须,取值为[general,generalv2]
*/
@JSONField(name = "domain")
@JSONField
// @Builder.Default
public String domain = "general";
/**
* 核采样阈值,用于决定结果随机性。取值越高随机性越强,即相同的问题得到的不同答案的可能性越高 - 非必须,取值为[0,1],默认0.5
*/
@JSONField(name = "temperature")
@JSONField
public float temperature = 0.5F;
/**
* 模型回答的tokens的最大长度 - 非必须,取值为[1,4096],默认2048
*/
@JSONField(name = "max_tokens")
@JSONField
public int max_tokens = 1024;
/**
* 从k个候选中随机选择⼀个(⾮等概率) - 非必须,取值为[1,6],默认4
*/
@JSONField(name = "top_k")
@JSONField
public int top_k = 4;
/**
* 用于关联用户会话 - 非必须,需要保障用户下的唯一性
*/
@JSONField(name = "chat_id") //, serialize = false)
public String chat_id;
@JSONField //, serialize = false)
public String chat_id; // FastJSON 对 null 值默认不序列化
}
}
@JSONField(name = "payload")
public Payload payload;
@JSONField
public Payload payload = new Payload();
public static class Payload {
@JSONField(name = "message")
public Message message;
@JSONField
public Message message = new Message();
@Data
public static class Message {
@JSONField(name = "text")
public List<Text> text;
@JSONField
public List<Text> text = new ArrayList<>();
@Data
public static class Text {
/**
* user表示用户的问题,assistant表示AI的回复 - 取值为[user,assistant]
*/
@JSONField(name = "role")
public String role;
@JSONField
public String role = "";
/**
* 用户和AI的对话内容 - 所有content的累计tokens需控制在8192以内
*/
@JSONField(name = "content")
public String content;
@JSONField
public String content = "";
public Text() {}
public Text(String role, String content) {
this.role = role;
this.content = content;
......
......@@ -17,54 +17,56 @@ import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
public class LLMResponseVO {
@JSONField(name = "header")
public Header header;
@JSONField
public Header header = new Header();
@Data
public static class Header {
/**
* 错误码,0表示正常,非0表示出错
*/
@JSONField(name = "code")
@JSONField
public int code;
/**
* 会话是否成功的描述信息
*/
@JSONField(name = "message")
public int message;
@JSONField
public String message;
/**
* 会话的唯一id,用于讯飞技术人员查询服务端会话日志使用
*/
@JSONField(name = "sid")
@JSONField
public String sid;
/**
* 会话状态,取值为[0,1,2];0代表首次结果;1代表中间结果;2代表最后一个结果
*/
@JSONField(name = "status")
@JSONField
public int status;
}
@JSONField(name = "payload")
public Payload payload;
@JSONField
public Payload payload = new Payload();
@Data
public static class Payload {
@JSONField(name = "choices")
public Choices choices;
@JSONField
public Choices choices = new Choices();
@Data
public static class Choices {
/**
* 文本响应状态,取值为[0,1,2]; 0代表首个文本结果;1代表中间文本结果;2代表最后一个文本结果
*/
@JSONField(name = "status")
@JSONField
public int status;
/**
* 返回的数据序号,取值为[0,9999999]
*/
@JSONField(name = "seq")
@JSONField
public int seq;
@JSONField(name = "text")
@JSONField
public List<Text> text;
@Data
......@@ -72,45 +74,45 @@ public class LLMResponseVO {
/**
* AI的回答内容
*/
@JSONField(name = "content")
@JSONField
public String content;
/**
* 角色标识,取值固定为assistant,标识角色为AI
*/
@JSONField(name = "role")
@JSONField
public String role;
// /**
// * 结果序号,取值为[0,10]; 当前为保留字段,开发者可忽略
// */
// @JSONField(name = "index")
// public int index;
/**
* 结果序号,取值为[0,10]; 当前为保留字段,开发者可忽略
*/
@JSONField
public int index;
}
}
@JSONField(name = "usage")
public Usage usage;
@JSONField
public Usage usage = new Usage();
@Data
public static class Usage {
// /**
// * 保留字段,可忽略
// */
// @JSONField(name = "question_tokens")
// public int question_tokens;
/**
* 保留字段,可忽略
*/
@JSONField
public int question_tokens;
/**
* 包含历史问题的总tokens大小
*/
@JSONField(name = "prompt_tokens")
@JSONField
public int prompt_tokens;
/**
* 回答的tokens大小
*/
@JSONField(name = "completion_tokens")
@JSONField
public int completion_tokens;
/**
* prompt_tokens和completion_tokens之和,即本次交互计费的tokens大小
*/
@JSONField(name = "total_tokens")
@JSONField
public int total_tokens;
}
}
......
......@@ -11,4 +11,8 @@ public class LLMServiceRequestVO {
this.userID = userID;
this.question = question;
}
public LLMServiceRequestVO(QueryRequestVO queryRequestVO) {
this.userID = queryRequestVO.userID;
this.question = queryRequestVO.question;
}
}
......@@ -11,4 +11,8 @@ public class LLMServiceResponseVO {
this.userID = userID;
this.answer = answer;
}
public LLMServiceResponseVO(QueryResponseVO queryResponseVO) {
this.userID = queryResponseVO.userID;
this.answer = queryResponseVO.answer;
}
}
package qiwu.xfllmdemo.pojo;
import java.util.Objects;
import java.util.UUID;
public class QueryRequestVO {
......@@ -12,4 +11,8 @@ public class QueryRequestVO {
this.userID = userID;
this.question = question;
}
public QueryRequestVO(LLMServiceRequestVO llmServiceRequestVO) {
this.userID = llmServiceRequestVO.userID;
this.question = llmServiceRequestVO.question;
}
}
......@@ -11,4 +11,8 @@ public class QueryResponseVO {
this.userID = userID;
this.answer = answer;
}
public QueryResponseVO(LLMServiceResponseVO llmServiceResponseVO) {
this.userID = llmServiceResponseVO.userID;
this.answer = llmServiceResponseVO.answer;
}
}
......@@ -7,9 +7,11 @@ 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.LLMRequestVO;
import qiwu.xfllmdemo.pojo.LLMRequestVO.Payload.Message;
import qiwu.xfllmdemo.pojo.LLMResponseVO;
......@@ -70,6 +72,7 @@ public class LLMService {
e.printStackTrace();
}
}
public static final Gson gson = new Gson();
/**
* 用于拼接整个回答串
......@@ -77,10 +80,10 @@ public class LLMService {
StringBuffer answerBuffer = new StringBuffer();
public LLMService() {
chatHistory = new HashMap<>();
}
public LLMServiceResponseVO query(LLMServiceRequestVO inVO) {
LLMServiceResponseVO outVO = new LLMServiceResponseVO();
// TODO 1. 根据入参获得用户id和对话历史
LinkedList<Message.Text> thisHistory = chatHistory.get(inVO.userID);
if (thisHistory == null) {
......@@ -88,19 +91,22 @@ public class LLMService {
thisHistory = new LinkedList<Message.Text>();
chatHistory.put(inVO.userID, thisHistory);
}
// TODO 2. 构造模型请求JSON
// TODO 2. 构造模型请求JSON,将问题添加到对话历史
LLMRequestVO toReq = new LLMRequestVO();
// toReq.header.uid = null;
toReq.header.app_id = appid;
toReq.parameter.chat.chat_id = inVO.userID.toString(); // 以UUID区分用户
thisHistory.add(new Message.Text("user", inVO.question));
toReq.payload.message.text = thisHistory;
String toReqJSON = JSON.toJSONString(toReq);
System.out.println(toReqJSON);
// TODO Test
System.out.println("toReqJSON: \n" + toReqJSON + "\n------");
System.out.println("authURL: \n" + authURL + "\n------");
// TODO 3. 发起请求,获得回复,将回复添加到对话历史,返回
LLMSocket llmSocket = new LLMSocket(authURL, toReqJSON);
StringBuffer ans = llmSocket.executeQuery();
String thisAnswer = llmSocket.executeQuery().toString();
thisHistory.add(new Message.Text("assistant", thisAnswer));
LLMServiceResponseVO outVO = new LLMServiceResponseVO(inVO.userID, thisAnswer);
return outVO;
}
}
......@@ -119,7 +125,8 @@ class LLMSocket extends WebSocketListener {
* 关闭WebSocket线程标志
*/
boolean wsCloseFlag = false;
StringBuffer output = new StringBuffer();
StringBuffer outBuffer = new StringBuffer();
static int threadNum = 0;
/**
* 建立连接,执行对模型的请求,并同步等待
......@@ -135,7 +142,7 @@ class LLMSocket extends WebSocketListener {
} catch (InterruptedException e) {
e.printStackTrace();
}
return output;
return outBuffer;
}
public LLMSocket(String authURL, String requestJSON) {
......@@ -174,6 +181,7 @@ class LLMSocket extends WebSocketListener {
super.onOpen(webSocket, response);
MonitorThread monitorThread = new MonitorThread();
monitorThread.start();
System.out.println("onOpen()");
}
/**
......@@ -182,20 +190,32 @@ class LLMSocket extends WebSocketListener {
* @param text
*/
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
// System.out.println(userId + "用来区分那个用户的结果" + text);
public synchronized void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
// System.out.println(userId + "用来区分是哪个用户的结果" + text);
// TODO Test
System.out.println("onMessage() " + threadNum + ": ");
threadNum++;
System.out.println("LLMResponseJSON: " + text);
// TODO 1. 解析返回的JSON,若出错处理
// 使用JSON.parseObject()时注意,传入的class中每个属性的类型必须与JSON字符串中严格相同,否则方法会阻塞且不会有任何异常抛出
LLMResponseVO responseVO = JSON.parseObject(text, LLMResponseVO.class);
if (responseVO.header.code != 0) {
System.out.println("发生错误,错误码为:" + responseVO.header.code);
System.out.println("本次请求的sid为:" + responseVO.header.sid);
webSocket.close(1000, "");
return;
}
// TODO 每个Response里面只有一个text?
// TODO Test
System.out.println("responseVO: " + responseVO);
// TODO 2. 提取其中的回答串
List<Choices.Text> textList = responseVO.payload.choices.text;
System.out.println(textList.size());
// TODO Test
System.out.println("textList.size(): " + textList.size());
// TODO 3. 拼接形成完整回答串 每个Response的test里面只有一个元素
for (Choices.Text temp : textList) {
System.out.print(temp.content);
output
System.out.println("temp.content: " + temp.content);
outBuffer.append(temp.content);
}
if (responseVO.header.status == 2) {
// 输出已结束,可以关闭连接,释放资源
......
已在 GitHub 上成功创建项目 'XfLLMDemo' ,但初始提交失败:
*** Please tell me who you are.
(cd到项目目录下) Run
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository. unable to auto-detect email address (got 'cyx@cyx-MS-7C83.(none)')
您即将把CRLF行分隔符提交到Git仓库。
建议将 core.autocrlf Git特性设置为input,以免发生行分隔符问题。
如果选择 修正并提交 ,将执行 git config --global core.autocrlf input。
如果选择 按原样提交 ,则不会更改配置值。
Lombok 要求已启用的注解处理 - 已启用的注解处理
!!!使用JSON.parseObject()时注意,传入的class中每个属性的类型必须与JSON字符串中严格相同,否则会导致方法阻塞且不会有任何异常抛出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>预生成回答</title>
</head>
<body>
<!-- <input type="file" id="videoUploader" accept="video/mp4, video/ogg">-->
<p id="uploadInfo">在此处上传预设用户话语txt</p>
<input type="file" id="textUploader" accept="text">
<button id="uploadBtn">上传</button>
<progress id="uploadProgress" value="0" max="100"></progress>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <!-- import axios -->
<script src="./pre-generate.js"></script>
</html>
\ No newline at end of file
// config.js
// 导出一些常量,包括上传信息、允许上传的文件类型、块大小和上传接口的URL
// 这些常量将在前端和后端代码中使用
const BASE_URL = 'http://localhost:8080';
/**
* dic - key : value
* @type {{UPLOAD_FAILED: string, NO_FILE: string, INVALID_TYPE: string, UPLOAD_SUCCESS: string}}
*/
export const UPLOAD_INFO = {
'NO_FILE': '请先选择文件',
'INVALID_TYPE': '不支持该类型文件上传',
'UPLOAD_FAILED': '上传失败',
'UPLOAD_SUCCESS': '上传成功'
}
export const ALLOWED_TYPE = {
// 'video/mp4': 'mp4',
// 'video/ogg': 'ogg'
'text': '文本文件'
}
export const CHUNK_SIZE = 64 * 1024;
export const API = {
UPLOAD_VIDEO: BASE_URL + '/uploadFile'
}
// index.js
// 在闭包内部,定义一个立即执行的匿名函数,接受document作为参数
((doc) => {
// 获取页面上的一些元素
const oProgress = doc.querySelector('#uploadProgress'); // 上传进度条
const oUploader = doc.querySelector('#videoUploader'); // 文件上传输入框
const oInfo = doc.querySelector('#uploadInfo'); // 用于显示上传信息
const oBtn = doc.querySelector('#uploadBtn'); // 上传按钮
let uploadedSize = 0; // 已上传的文件大小,用于控制分块上传
/**
* 初始化函数
*/
const init = () => {
bindEvent(); // 绑定事件
}
/**
* 绑定事件函数 - 为元素添加事件监听器
*/
function bindEvent() {
oBtn.addEventListener('click', uploadVideo, false); // 点击上传按钮触发上传函数
}
/**
* 异步上传函数
*/
async function uploadVideo() {
// 获取文件对象
const {files: [file]} = oUploader;
// 检查是否选择了文件,如果没有则显示提示信息
if (!file) {
oInfo.innerText = UPLOAD_INFO['NO_FILE'];
return;
}
// 检查文件类型是否被允许,如果不允许则显示提示信息
if (!ALLOWED_TYPE[file.type]) {
oInfo.innerText = UPLOAD_INFO['INVALID_TYPE'];
return;
}
// 获取文件的一些基本信息
const {name, type, size} = file;
const fileName = new Date().getTime() + '_' + name;
let uploadedResult = null;
oProgress.max = size;
oInfo.innerText = '';
while (uploadedSize < size) {
// 使用slice方法将文件切割成小块,实现分块上传
const fileChunk = file.slice(uploadedSize, uploadedSize + CHUNK_SIZE);
// 创建FormData对象,用于传递文件块和相关信息
const formData = createFormData({
name,
type,
size,
fileName,
uploadedSize,
file: fileChunk
});
// 使用axios库发送POST请求,将文件块上传到后端
try {
uploadedResult = await axios.post(API.UPLOAD_VIDEO, formData);
} catch (e) {
oInfo.innerText = `${UPLOAD_INFO['UPLOAD_FAILED']}(${e.message})`; // on Exception
return;
}
// 更新已上传的文件大小和进度条
uploadedSize += fileChunk.size;
oProgress.value = uploadedSize;
}
// 上传成功后,显示上传成功的提示信息,并将文件输入框置空
oInfo.innerText = UPLOAD_INFO['UPLOAD_SUCCESS'];
oUploader.value = null;
// 根据后端返回的视频URL,创建一个视频元素并展示在页面上
createVideo(uploadedResult.data.video_url);
}
/**
* 创建FormData函数,将文件块和相关信息添加到FormData对象中
*/
function createFormData({
name,
type,
size,
fileName,
uploadedSize,
file
}) {
const fd = new FormData();
fd.append('name', name);
fd.append('type', type);
fd.append('size', size);
fd.append('fileName', fileName);
fd.append('uploadedSize', uploadedSize);
fd.append('file', file);
return fd;
}
/**
* 创建视频元素函数,用于在页面上展示上传成功的视频
*/
function createVideo(src) {
const oVideo = document.createElement('video');
oVideo.controls = true;
oVideo.width = '500';
oVideo.src = src;
document.body.appendChild(oVideo);
}
// ------------------------------------
/**
* 初始化,执行绑定事件函数
*/
init();
}) (document);
......@@ -2,12 +2,27 @@ package qiwu.xfllmdemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import qiwu.xfllmdemo.pojo.LLMServiceRequestVO;
import qiwu.xfllmdemo.pojo.LLMServiceResponseVO;
import qiwu.xfllmdemo.service.LLMService;
import java.util.UUID;
@SpringBootTest
class XfLLMDemoApplicationTests {
@Test
// @Test
void contextLoads() {
}
@Test
void LLMServiceSingleQuestionTest() {
LLMService ls = new LLMService();
String question = "你今日饮咗未?";
LLMServiceRequestVO req = new LLMServiceRequestVO(UUID.fromString("6d7f4741-3bdb-40c8-a2d8-55b505fe6e2a"), question);
LLMServiceResponseVO resp = ls.query(req);
System.out.println("------- query() ends -------");
System.out.println("QueryResponseVO: " + resp/*.toString()*/);
System.out.println(resp.answer);
}
}
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