Skip to content

Commit 16f48cb

Browse files
committed
feat: 环境共享迁移完成
1 parent 48d5180 commit 16f48cb

File tree

6 files changed

+109
-78
lines changed

6 files changed

+109
-78
lines changed

apps/miniprogram-agent-ui/miniprogram/app.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ App({
1010
// env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
1111
// 此处请填入环境 ID, 环境 ID 可打开云控制台查看
1212
// 如不填则使用默认环境(第一个创建的环境)
13-
env: "luke-agent-dev-7g1nc8tqc2ab76af",
13+
env: "",
1414
traceUser: true,
1515
});
1616
}

apps/miniprogram-agent-ui/miniprogram/components/agent-ui/chatFile/index.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// components/agent-ui-new/chatFIle/chatFile.js
2+
import {getCloudInstance} from '../tools'
23
Component({
34
lifetimes: {
4-
attached: function () {
5+
attached: async function () {
56
console.log('enableDel', this.data.enableDel)
67
const { tempFileName, rawFileName, rawType, tempPath, fileId, botId, parsed } = this.data.fileData
78
const type = this.getFileType(rawFileName || tempFileName)
@@ -20,20 +21,21 @@ Component({
2021
})
2122
return
2223
}
23-
24+
const cloudInstance= await getCloudInstance()
25+
// console.log('file', cloudInstance)
2426
// 上传云存储获取 fileId
2527
// console.log('rawFileName tempFileName tempPath', rawFileName, tempFileName, tempPath)
26-
wx.cloud.uploadFile({
28+
cloudInstance.uploadFile({
2729
cloudPath: this.generateCosUploadPath(botId, rawFileName ? (rawFileName.split('.')[0] + '-' + tempFileName) : tempFileName), // 云上文件路径
2830
filePath: tempPath,
2931
success: async res => {
30-
const { token } = await wx.cloud.extend.AI.bot.tokenManager.getToken()
32+
const { token } = await cloudInstance.extend.AI.bot.tokenManager.getToken()
3133
const fileId = res.fileID
3234
this.setData({
3335
formatSize: '解析中',
3436
})
3537
wx.request({
36-
url: `https://${wx.cloud.extend.AI.bot.context.env}.api.tcloudbasegateway.com/v1/aibot/bots/${botId}/files`,
38+
url: `https://${cloudInstance.env||cloudInstance.extend.AI.bot.context.env}.api.tcloudbasegateway.com/v1/aibot/bots/${botId}/files`,
3739
data: {
3840
fileList: [{
3941
fileName: rawFileName || tempFileName,
@@ -182,7 +184,7 @@ Component({
182184
}
183185
})
184186
},
185-
openFile: function () {
187+
openFile: async function () {
186188
if (this.data.fileData.tempPath) {
187189
// 本地上传的文件
188190
if (this.data.fileData.rawType === 'file') {
@@ -195,7 +197,8 @@ Component({
195197
}
196198
} else if (this.data.fileData.fileId) {
197199
// 针对历史记录中带cloudID的处理(历史记录中附带的文件)
198-
wx.cloud.downloadFile({
200+
const cloudInsatnce=await getCloudInstance()
201+
cloudInsatnce.downloadFile({
199202
fileID: this.data.fileData.fileId,
200203
success: res => {
201204
console.log('download res', res)

apps/miniprogram-agent-ui/miniprogram/components/agent-ui/index.js

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
// components/agent-ui/index.js
2-
import { checkConfig, randomSelectInitquestion } from "./tools";
2+
import { checkConfig, randomSelectInitquestion,getCloudInstance } from "./tools";
33
import md5 from "./md5.js";
44
Component({
55
properties: {
66
chatMode: {
77
type: String,
88
value: "",
99
},
10-
aiInstance:{
10+
envShareConfig:{
1111
type:Object,
12-
value:null
12+
value:{
13+
resourceAppid:String,
14+
resourceEnv:String
15+
}
1316
},
1417
showBotAvatar: {
1518
type: Boolean,
@@ -103,10 +106,11 @@ Component({
103106
});
104107
return;
105108
}
109+
// 初始化一次cloudInstance,它是单例的,后面不传参数也可以获取到
110+
const cloudInstance=await getCloudInstance(this.data.envShareConfig)
106111
if (chatMode === "bot") {
107112
const { botId } = this.data.agentConfig;
108-
console.log(this.data.aiInstance)
109-
const ai = this.data.aiInstance||wx.cloud.extend.AI;
113+
const ai=cloudInstance.extend.AI;
110114
const bot = await ai.bot.get({ botId });
111115
// 新增错误提示
112116
if (bot.code) {
@@ -128,13 +132,13 @@ Component({
128132
// 随机选取三个初始化问题
129133
const questions = randomSelectInitquestion(bot.initQuestions, 3);
130134
let { allowWebSearch, allowUploadFile, allowPullRefresh, allowUploadImage, showToolCallDetail } = this.data.agentConfig;
131-
console.log("allowWebSearch", allowWebSearch);
135+
// console.log("allowWebSearch", allowWebSearch);
132136
allowWebSearch = allowWebSearch === undefined ? true : allowWebSearch;
133137
allowUploadFile = allowUploadFile === undefined ? true : allowUploadFile;
134138
allowPullRefresh = allowPullRefresh === undefined ? true : allowPullRefresh;
135139
allowUploadImage = allowUploadImage === undefined ? true : allowUploadImage;
136140
showToolCallDetail = showToolCallDetail === undefined ? true : showToolCallDetail
137-
console.log("allowUploadFile", allowUploadFile);
141+
// console.log("allowUploadFile", allowUploadFile);
138142
this.setData({
139143
bot,
140144
questions,
@@ -155,7 +159,7 @@ Component({
155159
methods: {
156160
showErrorMsg: function (e) {
157161
const { content, reqid } = e.currentTarget.dataset;
158-
console.log("content", content);
162+
// console.log("content", content);
159163
const transformContent =
160164
typeof content === "string"
161165
? reqid
@@ -211,7 +215,7 @@ Component({
211215
return transformToolCallList;
212216
},
213217
handleLineChange: function (e) {
214-
console.log("linechange", e.detail.lineCount);
218+
// console.log("linechange", e.detail.lineCount);
215219
// 查foot-function height
216220
const self = this;
217221
const query = wx.createSelectorQuery().in(this);
@@ -223,7 +227,7 @@ Component({
223227
textareaHeight: res.height,
224228
});
225229
} else {
226-
console.log("未找到指定元素");
230+
// console.log("未找到指定元素");
227231
}
228232
})
229233
.exec();
@@ -374,7 +378,8 @@ Component({
374378
page: newPage,
375379
});
376380
}
377-
const ai=this.data.aiInstance.extend.AI||wx.cloud.extend.AI
381+
const cloudInstance= await getCloudInstance(this.data.envShareConfig);
382+
const ai=cloudInstance.extend.AI;
378383
const res = await ai.bot.getChatRecords({
379384
botId: this.data.agentConfig.botId,
380385
pageNumber: this.data.page,
@@ -409,13 +414,13 @@ Component({
409414
transformItem.content = this.data.defaultErrorMsg;
410415
}
411416
if (item.role === "assistant" && item.origin_msg) {
412-
console.log("toolcall origin_msg", JSON.parse(item.origin_msg));
417+
// console.log("toolcall origin_msg", JSON.parse(item.origin_msg));
413418
const origin_msg_obj = JSON.parse(item.origin_msg);
414419
if (origin_msg_obj.aiResHistory) {
415420
const transformToolCallList = this.transformToolCallHistoryList(origin_msg_obj.aiResHistory);
416421
transformItem.toolCallList = transformToolCallList;
417422
const toolCallErr = transformToolCallList.find((item) => item.error)?.error;
418-
console.log("toolCallErr", toolCallErr);
423+
// console.log("toolCallErr", toolCallErr);
419424
if (toolCallErr?.error?.message) {
420425
transformItem.error = toolCallErr.error.message;
421426
transformItem.reqId = item.trace_id || "";
@@ -431,7 +436,7 @@ Component({
431436
this.setData({
432437
chatRecords: [...freshChatRecords, ...this.data.chatRecords],
433438
});
434-
console.log("totalChatRecords", this.data.chatRecords);
439+
// console.log("totalChatRecords", this.data.chatRecords);
435440
}
436441
this.setData({
437442
triggered: false,
@@ -479,8 +484,8 @@ Component({
479484
maxDuration: 30,
480485
camera: "back",
481486
success(res) {
482-
console.log("res", res);
483-
console.log("tempFiles", res.tempFiles);
487+
// console.log("res", res);
488+
// console.log("tempFiles", res.tempFiles);
484489
const isImageSizeValid = res.tempFiles.every((item) => item.size <= 30 * 1024 * 1024);
485490
if (!isImageSizeValid) {
486491
wx.showToast({
@@ -507,7 +512,7 @@ Component({
507512
});
508513

509514
const finalFileList = [...tempFiles];
510-
console.log("final", finalFileList);
515+
// console.log("final", finalFileList);
511516
self.setData({
512517
sendFileList: finalFileList, //
513518
});
@@ -549,22 +554,22 @@ Component({
549554
cancelText: "取消",
550555
confirmText: "确认",
551556
success(res) {
552-
console.log("res", res);
557+
// console.log("res", res);
553558
self.chooseMedia(sourceType);
554559
},
555560
fail(error) {
556-
console.log("choose file e", error);
561+
// console.log("choose file e", error);
557562
},
558563
});
559564
} else {
560565
self.chooseMedia(sourceType);
561566
}
562567
},
563568
chooseMessageFile: function () {
564-
console.log("触发choose");
569+
// console.log("触发choose");
565570
const self = this;
566571
const oldFileLen = this.data.sendFileList.filter((item) => item.rawType === "file").length;
567-
console.log("oldFileLen", oldFileLen);
572+
// console.log("oldFileLen", oldFileLen);
568573
const subFileCount = oldFileLen <= 5 ? 5 - oldFileLen : 0;
569574
if (subFileCount === 0) {
570575
wx.showToast({
@@ -579,7 +584,7 @@ Component({
579584
success(res) {
580585
// tempFilePath可以作为img标签的src属性显示图片
581586
// const tempFilePaths = res.tempFiles;
582-
console.log("res", res);
587+
// console.log("res", res);
583588
// 检验文件后缀
584589
const isFileExtValid = res.tempFiles.every((item) => self.checkFileExt(item.name.split(".")[1]));
585590
if (!isFileExtValid) {
@@ -777,7 +782,8 @@ Component({
777782
// 新增一轮对话记录时 自动往下滚底
778783
this.autoToBottom();
779784
if (chatMode === "bot") {
780-
const ai = this.data.aiInstance||wx.cloud.extend.AI;
785+
const cloudInstance = await getCloudInstance(this.data.envShareConfig);
786+
const ai=cloudInstance.extend.AI;
781787
const res = await ai.bot.sendMessage({
782788
data: {
783789
botId: bot.botId,
@@ -1000,7 +1006,8 @@ Component({
10001006
[`chatRecords[${lastValueIndex}].hiddenBtnGround`]: isManuallyPaused,
10011007
}); // 对话完成,切回0 ,并且修改最后一条消息的状态,让下面的按钮展示
10021008
if (bot.isNeedRecommend && !isManuallyPaused) {
1003-
const ai = this.data.aiInstance||wx.cloud.extend.AI;
1009+
const cloudInstance = await getCloudInstance(this.data.envShareConfig)
1010+
const ai=cloudInstance.extend.AI;
10041011
const chatRecords = this.data.chatRecords;
10051012
const lastPairChatRecord = chatRecords.length >= 2 ? chatRecords.slice(chatRecords.length - 2) : [];
10061013
const recommendRes = await ai.bot.getRecommendQuestions({
@@ -1029,8 +1036,8 @@ Component({
10291036
}
10301037
if (chatMode === "model") {
10311038
const { modelProvider, quickResponseModel } = modelConfig;
1032-
console.log('ryan',this.data.aiInstance)
1033-
const ai=this.data.aiInstance||wx.cloud.extend.AI
1039+
const cloudInstance= await getCloudInstance(this.data.envShareConfig)
1040+
const ai=cloudInstance.extend.AI;
10341041
const aiModel = ai.createModel(modelProvider);
10351042
const res = await aiModel.streamText({
10361043
data: {

apps/miniprogram-agent-ui/miniprogram/components/agent-ui/tools.js

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@ export const checkConfig = (chatMode,agentConfig,modelConfig) => {
22
const { botId } = agentConfig||{}
33
const { modelProvider,quickResponseModel,deepReasoningModel } = modelConfig||{}
44
// 检测不在微信环境,提示用户
5+
const appBaseInfo = wx.getAppBaseInfo();
56
try {
67
const systemInfo = wx.getSystemInfoSync()
7-
console.log('systemInfo', systemInfo)
8+
// console.log('systemInfo', systemInfo)
89
if(systemInfo.environment === 'wxwork') {
910
return [false,'请前往微信客户端扫码打开小程序']
1011
}
1112
}catch(e) {
12-
console.log('getSystemInfoSync 接口废弃')
13+
// console.log('getSystemInfoSync 接口废弃')
1314
// 使用 getAppBaseInfo 兜底
14-
const appBaseInfo = wx.getAppBaseInfo();
15-
console.log('appBaseInfo', appBaseInfo)
15+
// console.log('appBaseInfo', appBaseInfo)
1616
if(appBaseInfo.host.env === 'SDK') {
1717
return [false,'请前往微信客户端扫码打开小程序']
1818
}
1919
}
2020

2121
// 检测AI能力,不存在提示用户
22-
if(!wx.cloud.extend||!wx.cloud.extend.AI){
22+
if(compareVersions(appBaseInfo.SDKVersion,'3.7.7')<0){
2323
return [false,'使用AI能力需基础库为3.7.7及以上,请升级基础库版本或微信客户端']
2424
}
2525
if (!['bot', 'model'].includes(chatMode)) {
@@ -45,16 +45,46 @@ export function randomSelectInitquestion(question=[],num=3){
4545
}
4646
return Array.from(set)
4747
}
48-
function Throttle(){
49-
let timer=null
50-
return function(fn){
51-
if(!timer){
52-
timer=setTimeout(()=>{
53-
fn()
54-
timer=null
55-
},50)
48+
49+
export const getCloudInstance=(function(){
50+
let cloudInstance=null
51+
return async function(envShareConfig){
52+
if(cloudInstance){
53+
return cloudInstance
54+
}
55+
// 如果开启了环境共享,走环境共享的ai实例
56+
if(envShareConfig&&envShareConfig.resourceAppid&&envShareConfig.resourceEnv){
57+
let instance = new wx.cloud.Cloud({
58+
// 资源方 AppID
59+
resourceAppid: envShareConfig.resourceAppid,
60+
// 资源方环境 ID
61+
resourceEnv: envShareConfig.resourceEnv,
62+
})
63+
await instance.init()
64+
// 烦,环境共享时创建实例,没有把环境id挂在instance上,这里手动挂上去,如果你发现instance上有个env,那么这个insatnce就是环境共享的云开发实例
65+
instance.env=envShareConfig.resourceEnv
66+
cloudInstance=instance
67+
return cloudInstance
68+
}else{
69+
cloudInstance=wx.cloud
70+
return cloudInstance
5671
}
5772
}
58-
}
59-
// 频繁渲染会阻塞UI线程,这里节流一下
60-
export const ThrottleFn= Throttle()
73+
})()
74+
function compareVersions(version1, version2) {
75+
const v1Parts = version1.split('.').map(Number);
76+
const v2Parts = version2.split('.').map(Number);
77+
const maxLength = Math.max(v1Parts.length, v2Parts.length);
78+
79+
for (let i = 0; i < maxLength; i++) {
80+
const num1 = v1Parts[i] || 0;
81+
const num2 = v2Parts[i] || 0;
82+
83+
if (num1 > num2) {
84+
return 1;
85+
} else if (num1 < num2) {
86+
return -1;
87+
}
88+
}
89+
return 0;
90+
}

0 commit comments

Comments
 (0)