山东大学软件学院项目实训-创新实训-角色疆界

在与大模型对话中我们输入文本与文件,回车或按按钮发送提问。本文介绍项目中发送提问消息的函数的设计,展示其中的要点。

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、相关函数的具体实现略

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值