在与大模型对话中我们输入文本与文件,回车或按按钮发送提问。本文介绍项目中发送提问消息的函数的设计,展示其中的要点。
1、提问合法性判断:消息不为空且没有对话在加载
if (this.chatMsg.trim().length == 0) {
return; // 如果消息为空,则不发送
}
if (this.convLoading) {
alert("当前消息正在加载,请耐心等待!")
return; // 如果当前会话正在加载,则不发送消息
}
2、设置会话为加载状态,不允许在会话加载时发送消息
this.convLoading = true;
3、消息处理
var chatMsg = this.chatMsg; // 获取消息
chatMsg = chatMsg.trim().replace(/\n/g, ""); // 去除消息中的换行符
this.chatMsg = ""; // 清空消息输入框
4、若提问携带文件,将文件编码成与后端适配的base64格式
//对单个文件编码
const readFileAsDataURL = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) => reject(e);
reader.readAsDataURL(file);
});
};
//对文件列表编码,保存到image_list
const encodeFiles = async () => {
for (const [file_id, file] of Object.entries(file_list)) {
console.log(file_id, typeof file, file.name, file instanceof File);
show_file_list[file_id] = file.name;
const base64String = await readFileAsDataURL(file);
image_list.push(base64String);
}
return image_list;
};
5、发送提问消息
axios.post('http://localhost:7860/generate',{
"prompt":chatMsg,
"image_list":image_list,
})
.then...
响应后处理:
(1)对话内容持久化,保存到数据库
var content = response.data.response; // 获取接收到的数据
axios.post('http://127.0.0.1:5000/save', {
cid: this.cid,
human: chatMsg,
file_list:show_file_list,
has_file:has_file,
ai:content
})
.then(response => {
console.log('对话保存成功',response.data);
})
.catch(error => {
console.error('对话保存错误:', error);
});
(2)内容展示到聊天框、对话状态设置、会话刷新等略
(3)若当前会话第一次发消息,则需要会话生成相关处理
if (first) { // 如果这是第一次发送消息
// 创建一个新的会话对象
var newConv = {
"id": that.cid,
"title": "New chat"
};
that.generateConvTitle(newConv,chatMsg); // 生成新的会话标题
that.conversations.unshift(newConv);// 将新的对话添加到会话的对话列表的开头
that.selectConversation(newConv, false);//选择新会话
that.saveConversations(); // 保存会话列表
that.refrechConversation(); // 刷新会话内容
return;
}
(4)其他处理...
6、相关函数的具体实现略