feat: 添加AI智能客服弹窗组件(对接扣子API)
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
module.exports = {
|
||||
main: async (event) => {
|
||||
let { data = {}, userInfo } = event;
|
||||
|
||||
const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG';
|
||||
const BOT_ID = '7680345813062680618';
|
||||
|
||||
// 使用流式接口,直接从 SSE 事件中提取回答
|
||||
const res = await uniCloud.httpclient.request('https://api.coze.cn/v3/chat', {
|
||||
method: 'POST',
|
||||
dataType: 'text',
|
||||
contentType: 'json',
|
||||
timeout: 120000,
|
||||
headers: { 'Authorization': 'Bearer ' + COZE_TOKEN },
|
||||
data: {
|
||||
bot_id: BOT_ID,
|
||||
user_id: (userInfo && userInfo.uid) || 'anonymous',
|
||||
stream: true,
|
||||
auto_save_history: true,
|
||||
additional_messages: [{
|
||||
role: 'user',
|
||||
content: data.message,
|
||||
content_type: 'text'
|
||||
}]
|
||||
}
|
||||
});
|
||||
|
||||
// 从 SSE 文本中提取 type=answer 的内容
|
||||
let answer = '暂时无法回复,请拨打 400-686-5559 咨询';
|
||||
let conversationId = '';
|
||||
const text = res.data || '';
|
||||
|
||||
const lines = text.split('\n');
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data:')) continue;
|
||||
const d = line.slice(5).trim();
|
||||
if (d === '[DONE]' || d === '"[DONE]"') continue;
|
||||
try {
|
||||
const p = JSON.parse(d);
|
||||
if (p.conversation_id) conversationId = p.conversation_id;
|
||||
if (p.type === 'answer' && p.content) {
|
||||
answer = p.content;
|
||||
}
|
||||
} catch (e) { /* 跳过非 JSON 行 */ }
|
||||
}
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
msg: 'ok',
|
||||
data: { answer, conversation_id: conversationId }
|
||||
};
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user