You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SCASS_project/message/message.js

98 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

Page({
data: {
messages: [], // 用于存储消息内容
inputVal: '', // 用户输入的内容
},
// 生成唯一ID函数
generateUniqueId() {
return 'msg_' + new Date().getTime() + Math.floor(Math.random() * 1000);
},
// 发送用户消息
sendMessage() {
const that = this;
// 检查输入框内容是否为空
if (this.data.inputVal === '') {
wx.showToast({
title: '请输入内容',
icon: 'none'
});
return;
}
// 添加用户消息并生成唯一ID
const userMessage = {
id: this.generateUniqueId(),
role: 'user',
content: this.data.inputVal
};
// 更新消息列表,并清空输入框内容
this.setData({
messages: [...this.data.messages, userMessage],
inputVal: '' // 清空输入框内容
});
// 调用腾讯混元 API 获取回复,传递所有消息历史
wx.request({
url: 'https://yuanqi.tencent.com/openapi/v1/agent/chat/completions', // API地址
method: 'POST',
data: {
assistant_id: 'XEpMRFLn0yqm', // 替换为你的 assistant_id
user_id: '<userid>', // 替换为实际的用户ID
stream: false,
messages: that.data.messages.map(msg => ({
role: msg.role,
content: [
{
type: 'text',
text: msg.content
}
]
}))
},
header: {
'X-Source': 'openapi', // 必需的X-Source头部
'Content-Type': 'application/json',
'Authorization': 'Bearer K8xhMFEsRpO00MKFKRUqeyideA0Ego3a' // 替换为你的API密钥
},
success(res) {
if (res.data && res.data.choices && res.data.choices.length > 0) {
const assistantMessage = {
id: that.generateUniqueId(), // 为助手消息生成唯一ID
role: 'assistant',
content: res.data.choices[0].message.content
};
// 添加助手消息
that.setData({
messages: [...that.data.messages, assistantMessage]
});
} else {
wx.showToast({
title: 'API返回异常',
icon: 'none'
});
}
},
fail(response) {
console.log('请求失败:', response); // 输出失败信息用于调试
wx.showToast({
title: '请求失败请检查网络或API密钥',
icon: 'none'
});
}
});
},
// 处理用户输入
bindKeyInput(e) {
this.setData({
inputVal: e.detail.value
});
}
});