52 lines
1.5 KiB
JavaScript
52 lines
1.5 KiB
JavaScript
module.exports = {
|
|
main: async (event) => {
|
|
let { data = {}, userInfo } = event;
|
|
|
|
const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG';
|
|
// 从前端传入 bot_id,不同项目用不同智能体
|
|
const BOT_ID = data.bot_id || '7680345813062680618';
|
|
|
|
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'
|
|
}]
|
|
}
|
|
});
|
|
|
|
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) { /* 跳过 */ }
|
|
}
|
|
|
|
return {
|
|
code: 0,
|
|
msg: 'ok',
|
|
data: { answer, conversation_id: conversationId }
|
|
};
|
|
}
|
|
};
|