module.exports = { main: async (event) => { let { data = {}, userInfo } = event; const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG'; const BOT_ID = '7689821072762011698'; let fileId = data.file_id; // 模式1:只上传文件(选文件时调用) if (data.upload_only && data.file_base64) { const fileBuffer = Buffer.from(data.file_base64, 'base64'); const boundary = '----FormBoundary' + Date.now(); const header = Buffer.from( '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="file"; filename="' + (data.file_name || 'file') + '"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n' ); const footer = Buffer.from('\r\n--' + boundary + '--\r\n'); const uploadBody = Buffer.concat([header, fileBuffer, footer]); try { const uploadRes = await uniCloud.httpclient.request('https://api.coze.cn/v1/files/upload', { method: 'POST', dataType: 'json', headers: { 'Authorization': 'Bearer ' + COZE_TOKEN, 'Content-Type': 'multipart/form-data; boundary=' + boundary, 'Content-Length': uploadBody.length.toString() }, content: uploadBody, timeout: 60000 }); if (uploadRes.data.code !== 0) { return { code: -1, msg: '文件上传失败: ' + uploadRes.data.msg }; } fileId = uploadRes.data.data.id; return { code: 0, msg: 'ok', data: { file_id: fileId } }; } catch (e) { return { code: -1, msg: '上传异常: ' + e.message }; } } // 模式2:发起审查(不等结果,立即返回 chat_id) if (!fileId) { return { code: -1, msg: '缺少 file_id' }; } const objectString = JSON.stringify([ { type: 'file', file_id: fileId }, { type: 'text', text: '请审查这份合同' } ]); try { const chatRes = await uniCloud.httpclient.request('https://api.coze.cn/v3/chat', { method: 'POST', dataType: 'json', contentType: 'json', timeout: 30000, headers: { 'Authorization': 'Bearer ' + COZE_TOKEN }, data: { bot_id: BOT_ID, user_id: (userInfo && userInfo.uid) || 'anonymous', stream: false, auto_save_history: true, additional_messages: [{ role: 'user', content: objectString, content_type: 'object_string' }] } }); const chatData = chatRes.data && chatRes.data.data; return { code: 0, msg: 'ok', data: { chat_id: chatData && chatData.id, conversation_id: chatData && chatData.conversation_id } }; } catch (e) { return { code: -1, msg: '审查发起失败: ' + e.message }; } } };