index.obj.js 8.8 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1
// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
DCloud_JSON's avatar
DCloud_JSON 已提交
2 3 4 5 6 7
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const {safeRequire, checkContentSecurityEnable} = require('./utils')
const createConfig = safeRequire('uni-config-center')
const config = createConfig({
	pluginId: 'uni-ai-chat'
}).config()
8 9 10
const db = uniCloud.database();
const userscollection = db.collection('uni-id-users')
const uniIdCommon = require('uni-id-common')
DCloud_JSON's avatar
DCloud_JSON 已提交
11

DCloud_JSON's avatar
DCloud_JSON 已提交
12 13
module.exports = {
	_before:async function() {
14
		// 这里是云函数的前置方法,你可以在这里加入你需要逻辑,比如:
DCloud_JSON's avatar
DCloud_JSON 已提交
15 16 17 18 19 20 21
		/*
			例如:使用uni-id-pages(链接地址:https://ext.dcloud.net.cn/plugin?id=8577)搭建账户体系。
			然后再使用uni-id-common的uniIdCommon.checkToken判断用户端身份,验证不通过你可以直接`throw new Error(“token无效”)`抛出异常拦截访问。
			如果验证通过了可以获得用户id,可以记录每一个用户id的调用次数来限制,调用多少次后必须充值(推荐用uni-pay,下载地址:https://ext.dcloud.net.cn/plugin?id=1835)
			或者看一个激励视频广告(详情:https://uniapp.dcloud.net.cn/uni-ad/ad-rewarded-video.html)后才能继续使用
			*** 激励视频是造富神器。行业经常出现几个人的团队,月收入百万的奇迹。 ***
		*/
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
	   
		if(this.getMethodName() == 'send'){
			// 从配置中心获取是否需要销毁积分
			if(config.needReduceScore){
				
			/*先校验token(用户身份令牌)是否有效,并获得用户的_id*/
				// 获取客户端信息
				this.clientInfo = this.getClientInfo()
				// console.log(this.clientInfo);
				
				// 定义uni-id公共模块对象
				this.uniIdCommon = uniIdCommon.createInstance({
					clientInfo: this.clientInfo
				})
				let res = await this.uniIdCommon.checkToken(this.clientInfo.uniIdToken)
				if (res.errCode) {
					// 如果token校验出错,则抛出错误
					throw res
				}else{
					// 通过token校验则,拿去用户id
					this.current_uid = res.uid
DCloud_JSON's avatar
DCloud_JSON 已提交
43
				}
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
			/* 判断剩余多少积分:拒绝对话、扣除配置的积分数 */
				let {data:[{score}]} = await userscollection.doc(this.current_uid).field({'score':1}).get()
				console.log('score----',score);
				if(score == 0 || score < 0){ //并发的情况下可能花超过
					throw "insufficientPoints"
				}
				await userscollection.doc(this.current_uid)
						.update({
							score:db.command.inc(-1 * config.needReduceScore)
						})
			}
			
			// 从配置中心获取内容安全配置
			if (config.contentSecurity) {
				const UniSecCheck = safeRequire('uni-sec-check')
				const uniSecCheck = new UniSecCheck({
					provider: 'mp-weixin',
					requestId: this.getUniCloudRequestId()
DCloud_JSON's avatar
DCloud_JSON 已提交
62
				})
63 64 65 66
				this.textSecCheck = async (content)=>{
					let {SSEChannel} = this.getParams()[0]||{}
					if(SSEChannel){
						return console.log('提示:流式响应模式,内容安全识别功能无效');
DCloud_JSON's avatar
DCloud_JSON 已提交
67
					}
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
					// 检测文本
					const checkRes = await uniSecCheck.textSecCheck({
						content,
						// openid,
						scene:4,
						version:1 //后续:支持微信登录后,微信小程序端 改用模式2 详情:https://uniapp.dcloud.net.cn/uniCloud/uni-sec-check.html#%E4%BD%BF%E7%94%A8%E5%89%8D%E5%BF%85%E7%9C%8B
					})
					console.log('checkRes检测文本',checkRes);
					if (checkRes.errCode === uniSecCheck.ErrorCode.RISK_CONTENT) {
						console.error({
							errCode: checkRes.errCode,
							errMsg: '文字存在风险',
							result: checkRes.result
						});
						throw "isSecCheck"
					} else if (checkRes.errCode) {
						console.log(`其他原因导致此文件未完成自动审核(错误码:${checkRes.errCode},错误信息:${checkRes.errMsg}),需要人工审核`);
						console.error({
							errCode: checkRes.errCode,
							errMsg: checkRes.errMsg,
							result: checkRes.result
						});
						throw "isSecCheck"
DCloud_JSON's avatar
DCloud_JSON 已提交
91 92
					}
				}
93 94 95 96 97
				
				let {messages} = this.getParams()[0]||{"messages":[]}
				let contentString = messages.map(i=>i.content).join(' ')
				console.log('contentString',contentString);
				await this.textSecCheck(contentString)
DCloud_JSON's avatar
DCloud_JSON 已提交
98
			}
99
		}
DCloud_JSON's avatar
DCloud_JSON 已提交
100 101 102
	},
	async _after(error, result) {
		if(error){
103
			if(error == "isSecCheck" ) {
DCloud_JSON's avatar
DCloud_JSON 已提交
104 105 106 107 108 109
				return {
					"data": {
						"reply": "内容涉及敏感"
					},
					"errCode": 0
				}
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
			}else if(error == 'insufficientPoints'){
				let reply = "积分不足,请看完激励视频广告后再试"
				let {SSEChannel} = this.getParams()[0]||{}
				if(SSEChannel){
					const channel = uniCloud.deserializeSSEChannel(SSEChannel)
					await channel.write(reply)
					await channel.end({
						"insufficientPoints":true
					})
					
				}else{
					return {
						"data": {
							reply,
							"insufficientPoints":true
						},
						"errCode": 0
					}
				}
DCloud_JSON's avatar
DCloud_JSON 已提交
129 130
			}else{
				throw error // 直接抛出异常
DCloud_JSON's avatar
DCloud_JSON 已提交
131 132 133
			}
		}
		
DCloud_JSON's avatar
DCloud_JSON 已提交
134 135 136 137 138 139 140 141 142 143 144
		if (this.getMethodName() == 'send' && config.contentSecurity) {
			try{
				await this.textSecCheck(result.data.reply)
			}catch(e){
				return {
					"data": {
						"reply": "内容涉及敏感"
					},
					"errCode": 0
				}
			}
DCloud_JSON's avatar
DCloud_JSON 已提交
145
		}
DCloud_JSON's avatar
DCloud_JSON 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
		return result
	},
	async send({
		messages,
		SSEChannel
	}) {
		// 初次调试时,可不从客户端获取数据,直接使用下面写死在云函数里的数据
		// messages =  [{
		// 	role: 'user',
		// 	content: 'uni-app是什么,20个字以内进行说明'
		// }]

		// 校验客户端提交的参数
		let res = checkMessages(messages)
		if (res.errCode) {
			throw new Error(res.errMsg)
		}

164 165 166 167 168 169
		// 向uni-ai发送消息
		let {llm,chatCompletionOptions} = config
		return await chatCompletion({
			messages, //消息内容
			SSEChannel, //sse渠道对象
			llm
DCloud_JSON's avatar
DCloud_JSON 已提交
170 171 172 173 174
		})
		async function chatCompletion({
			messages,
			summarize = false,
			SSEChannel = false,
175 176 177 178 179 180
			llm
		}) {
			
			const llmManager = uniCloud.ai.getLLMManager(llm)
			let res = await llmManager.chatCompletion({
				...chatCompletionOptions,
DCloud_JSON's avatar
DCloud_JSON 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
				messages,
				stream: SSEChannel !== false
			})

			if (SSEChannel) {
				let reply = ""
				return new Promise((resolve, reject) => {
					const channel = uniCloud.deserializeSSEChannel(SSEChannel)
					res.on('message', async (message) => {
						// await channel.write(message)
						// console.log('---message----', message)
					})
					res.on('line', async (line) => {
						reply += line
						await channel.write(line)
						// console.log('---line----', line)
					})
					res.on('end', async () => {
						// console.log('---end----',reply)

						messages.push({
							"content": reply,
							"role": "assistant"
						})

						let totalTokens = messages.map(i => i.content).join('').length;
						// console.log('totalTokens',totalTokens);
						if (!summarize && totalTokens > 500) {
							let replySummarize = await getSummarize(messages)
							// console.log('replySummarize',replySummarize)
							await channel.end({
								summarize: replySummarize
							})
						} else {
							await channel.end()
						}
						resolve({
							errCode: 0
						})
					})
					res.on('error', (err) => {
						console.error('---error----', err)
						reject(err)
					})
				})
			} else {
				if (summarize == false) {
					messages.push({
						"content": res.reply,
						"role": "assistant"
					})
					let totalTokens = messages.map(i => i.content).join('').length;
					if (totalTokens > 500) {
						let replySummarize = await getSummarize(messages)
						res.summarize = replySummarize
					}
DCloud_JSON's avatar
DCloud_JSON 已提交
237
				}
DCloud_JSON's avatar
DCloud_JSON 已提交
238 239
				if(res.errCode){
					throw res
DCloud_JSON's avatar
DCloud_JSON 已提交
240 241
				}
				return {
DCloud_JSON's avatar
DCloud_JSON 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
					data:res,
					errCode: 0
				}
			}
		}

		//获总结
		async function getSummarize(messages) {
			messages.push({
				"content": "请简要总结上述全部对话",
				"role": "user"
			})
			// 获取总结不需要再总结summarize和stream
			let res = await chatCompletion({
				messages,
				summarize: true,
				stream: false,
				SSEChannel: false
			})
			return res.reply
		}

		function checkMessages(messages) {
			try {
				if (messages === undefined) {
					throw "messages为必传参数"
				} else if (!Array.isArray(messages)) {
					throw "参数messages的值类型必须是[object,object...]"
				} else {
					messages.forEach(item => {
						if (typeof item != 'object') {
							throw "参数messages的值类型必须是[object,object...]"
						}
						let itemRoleArr = ["assistant", "user", "system"]
						if (!itemRoleArr.includes(item.role)) {
							throw "参数messages[{role}]的值只能是:" + itemRoleArr.join('')
						}
						if (typeof item.content != 'string') {
							throw "参数messages[{content}]的值类型必须是字符串"
						}
					})
				}
				return {
					errCode: 0,
				}
			} catch (errMsg) {
				return {
					errSubject: 'ai-demo',
					errCode: 'param-error',
					errMsg
				}
			}
DCloud_JSON's avatar
DCloud_JSON 已提交
294 295 296
		}
	}
}