微信小程序和H5端对接dify ai接口
用的uniapp开发的
H5端是基于SSE协议开发的
要安装
import {
fetchEventSource
} from '@microsoft/fetch-event-source';
/*#ifdef H5*/
const eventSource = new fetchEventSource('/v1/chat-messages', {
method: 'POST',
headers: {
'Authorization': 'Bearer app-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: {},
query: message, // 替换为实际的查询内容
response_mode: 'streaming', // 启用流式响应
conversation_id: that.conversationId,
user: "abc-123"
}),
onopen(response) {
// 建立连接
console.log(response, "open");
if (response.ok) {
console.log("成功建立连接");
} else {
throw new Error(JSON.stringify(response));
}
},
onmessage(event) {
try {
const jsonData = JSON.parse(event.data);
if (jsonData.event === "message") {
//that.loading = false; // 隐藏加载图标
that.conversationId = jsonData.conversation_id;
// 如果返回的答案中有新的文字,逐字显示
if (jsonData.answer) {
// 追加接收到的新文字
that.displayedText += jsonData.answer;
// 继续显示新的文字
//that.startTyping(jsonData.message_id);
}
}
console.log("that.displayedText", that.displayedText);
if (jsonData.event === "message_end") {
that.loading = false; // 隐藏加载图标
that.arr.push({
answer: that.displayedText,
message_id: jsonData.message_id,
});
that.displayedText = "";
console.log("that.arr", that.arr);
}
} catch (error) {
console.error("数据解析错误:", error);
}
},
onclose() {
console.log("关闭链接");
},
onerror(err) {
console.error("发生错误", err);
throw err;
},
openWhenHidden: true, // 实时通知
});
/*#endif*/
/*#ifdef MP-WEIXIN*/
// 微信小程序端执行的逻辑
const requestTask = uni.request({
url: '/v1/chat-messages',
timeout: 15000,
responseType: 'text',
method: 'POST',
header: {
'Authorization': 'Bearer app-xxx',
'Content-Type': 'application/json',
},
enableChunked: true, //配置这里
data: JSON.stringify({
inputs: {},
query: message, // 替换为实际的查询内容
response_mode: 'streaming', // 启用流式响应
conversation_id: that.conversationId,
user: "abc-123"
}),
success: response => {
console.log(response)
},
fail: error => {}
})
requestTask.onHeadersReceived(function(res) {
console.log(res.header);
});
// 这里监听消息
requestTask.onChunkReceived(function(res) {
let decoder = new TextDecoder('utf-8')
let text = decoder.decode(new Uint8Array(res.data))
console.log(text)
try {
// 使用正则表达式去除前缀 "data: "
const jsonString = text.replace(/^data:\s*/, '');
const jsonData = JSON.parse(jsonString);
if (jsonData.event === "message") {
//that.loading = false; // 隐藏加载图标
that.conversationId = jsonData.conversation_id;
// 如果返回的答案中有新的文字,逐字显示
if (jsonData.answer) {
// 追加接收到的新文字
that.displayedText += jsonData.answer;
// 继续显示新的文字
//that.startTyping(jsonData.message_id);
}
}
console.log("that.displayedText", that.displayedText);
if (jsonData.event === "message_end") {
that.loading = false; // 隐藏加载图标
that.arr.push({
answer: that.displayedText,
message_id: jsonData.message_id,
});
that.displayedText = "";
console.log("that.arr", that.arr);
}
} catch (error) {
console.error("数据解析错误:", error);
}
})
/*#endif*/