gerson
2024-08-11 b2b8e5ed16f139597b10452df0c467b6e7cde500
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
237
238
239
240
241
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import {
  AnswerState,
  AnswerType,
  ChatContent,
  ChatMessage,
  RoleEnum,
  roleImageMap
} from "@/model/chat/types";
import {
  CHAT_GROUP_DATA,
  TEST_DATA
} from "./testData";
import {
  TAB_BAR_HEIGHT
} from "@/custom-tab-bar/constants";
import {
  checkAuth
} from "@/utils/http";
import { CreateHistoryGroup, DeleteHistoryGroups, extCallQuery, GetHistoryAnswer, GetHistoryGroups, getQuestionProcess, getSelectSample, QueryHistoryDetail, QuestionAi, setHistoryGroupTitle } from "@/api/chat";
 
import { ErrorCode } from "@/utils/http";
import { ComponentWithComputed, } from "miniprogram-computed";
import { uuid } from "@/utils/uuid";
import { getStorage } from "@/utils/storage";
 
const app = getApp();
// pages/question/question.js
const getAnswerById = async (historyId: string) => {
  return await GetHistoryAnswer({
    history_id: historyId,
  });
};
const DEFAULT_SECTION_A_ID = 'knowledge_base'
 
const parseContent = (res) => {
  if (!res) return null;
  let content: ChatContent = {
    type: AnswerType.Text,
    values: '解析失败!',
  };
 
  switch (res.answer_type) {
    case AnswerType.RecordSet:
      content = {
        type: AnswerType.RecordSet,
        values: res.values,
      };
      break;
    case AnswerType.Text:
      content = {
        type: AnswerType.Text,
        values: res.values ?? res.answer,
      };
      break;
 
    case AnswerType.Knowledge:
      content = {
        type: AnswerType.Knowledge,
        values: res.knowledge,
      };
 
      break;
    case AnswerType.Summary:
      content = {
        type: AnswerType.Summary,
        values: res.summary,
      };
 
      break;
    case AnswerType.Url:
      content = {
        type: AnswerType.Url,
        values: res.url,
      };
      break;
    case AnswerType.Map:
      content = {
        type: AnswerType.Map,
        values: res.values,
      };
      break;
    default:
      content = {
        type: AnswerType.Text,
        values: '解析失败!',
      };
      break;
  }
  content.askMoreList = wx.$_.orderBy(res.context_history, [(item) => Number(item.radio)], ['desc']);
  content.errCode = res?.err_code;
  content.errMsg = res?.json_msg;
  content.origin = res;
  return content;
};
 
 
 
let processId = '';
const QUERY_PROCESS_INTERVAL = 1000;
let processTimer = null;
let finishProcess = true;
 
 
 
 
 
 
 
Page({
 
 
 
  // 页面的初始数据
  data: {
    isTalking: false,
    AnswerType,
    sendText: '你是谁?',
    chatHistory: [],
    roleImageMap,
    RoleEnum,
    drawerIsShow: false,
    chatRoomList: [],
    toViewId: '',
    TAB_BAR_HEIGHT: TAB_BAR_HEIGHT,
    ErrorCode,
    questionRes: null,
    activeChatRoom: {
    },
    processText: '',
    /** @description 所有得sample */
    sampleList: [],
    /** @description 随机抽出最多三个例子 */
    displaySampleList: [],
    section_a_id: '',
    sample_id: '',
    userName:getStorage('username'),
 
  },
  onClickClear(){
    console.log('clear');
    
    this.setData({
      sendText:''
    })
  },
  async getSampleList() {
    const res = await getSelectSample({
      section_b_id: '',
    });
    this.setData({
      sampleList: res?.samples ?? []
    })
    this.setData({
      displaySampleList: wx.$_.sampleSize(this.data.sampleList, 3)
    })
  },
  sampleClick(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      sample_id: item.sample_id,
      sendText: item.sample_question,
      section_a_id: item.section_a_id,
    })
  },
  queryProcess() {
    processTimer = setInterval(() => {
      if (!finishProcess) return;
      finishProcess = false;
      this.queryProcessApi();
    }, QUERY_PROCESS_INTERVAL);
  },
  async queryProcessApi() {
    const res = await getQuestionProcess({
      process_id: processId,
    }, {
      isLoading: false
    }).catch((err) => {
      this.setData({
        processText: err
      })
    });
    this.setData({
      processText: res.process
    })
    finishProcess = true;
  },
  clearQueryProcess() {
    this.setData({
      processText: ''
    })
    clearInterval(processTimer);
  },
  async questionAi(text) {
    // if (!currentSectionId) {
    //   ElMessage.warning('发送失败,未确定应用场景!');
    // }
    processId = uuid();
    // const judgeParams = !preQuestion.value
    //   ? {}
    //   : {
    //       prev_question: preQuestion.value,
    //     };
    let currentSectionAId = '';
    if (this.data.section_a_id) {
      currentSectionAId = this.data.section_a_id;
      this.data.section_a_id = '';
    } else {
      const lastSectionAItem = wx.$_.findLast(this.data.chatHistory, (item) => item.role === RoleEnum.assistant && !!item.sectionAId);
      currentSectionAId = lastSectionAItem?.sectionAId ?? DEFAULT_SECTION_A_ID;
    }
    const judgeParams = {}
    const params = {
      process_id: processId,
      question: text,
      section_a_id: currentSectionAId,
      history_group_id: this.data.activeChatRoom.id,
      raw_mode: false,
      ...judgeParams,
    } as any;
    if (this.data.sample_id) {
      params.sample_id = this.data.sample_id;
      this.data.sample_id = '';
    }
 
    // if (currentLLMId) {
    //   params.llm_id = currentLLMId;
    // }
    this.clearQueryProcess();
    this.queryProcess();
    const res = await QuestionAi(params, {
      isLoading: false
    }).finally(() => {
      this.clearQueryProcess();
    });
    this.questionRes = res;
    const content = parseContent(res);
    return content;
  },
  async sendText(cb?: any, callExtParams?: any) {
    if (!this.data.sendText || this.data.isTalking) return;
    let resMsgContent: ChatContent = null;
    const isInitial = this.data.activeChatRoom.isInitial;
    if (isInitial) {
      this.data.activeChatRoom.isInitial = false;
      this.setData({
        activeChatRoom: this.data.activeChatRoom
      })
      /** @description 修改聊天室名称 */
      const res = await setHistoryGroupTitle({
        history_group_id: this.data.activeChatRoom.id,
        title: this.data.sendText,
      }, {
        isLoading: false
      });
      if (!res?.json_ok) return;
      this.data.activeChatRoom.title = this.data.sendText;
      wx.setNavigationBarTitle({
        title: this.data.activeChatRoom.title
      })
      this.setData({
        chatRoomList: this.data.chatRoomList
      })
    }
    try {
 
      const userItem: ChatMessage = {
        role: RoleEnum.user, content: {
          type: AnswerType.Text,
          values: this.data.sendText
        }
      } as any;
      const assistantItem: ChatMessage = { role: RoleEnum.assistant, content: null, state: AnswerState.Null } as any;
 
 
      // 发送当前
      this.data.chatHistory.push(userItem);
      const currentText = this.data.sendText;
 
      // 清空输入框
      this.setData({
        sendText: '',
      })
      // 出现回复,等待恢复对话
      this.setData({
        isTalking: true
      })
      this.data.chatHistory.push(assistantItem);
      this.setData({
        chatHistory: this.data.chatHistory
      })
      this.scrollToBottom();
      if (callExtParams) {
        const extRes = await extCallQuery(callExtParams);
        this.questionRes = extRes;
        resMsgContent = parseContent(extRes);
      } else {
        resMsgContent = await this.questionAi(currentText);
      }
      userItem.historyId = this.questionRes.history_id;
      assistantItem.historyId = this.questionRes.history_id;
      this.data.chatHistory[this.data.chatHistory.length - 1].content = resMsgContent
      this.setData({
        chatHistory: this.data.chatHistory
      })
      this.scrollToBottom();
    } catch (error: any) {
    } finally {
      this.setData({
        isTalking: false
      })
    }
  },
  inputRighBtnClick() {
    if (this.data.sendText) {
      this.sendText();
    } else {
 
    }
  },
  async newChatRoomClick(isLoading = true) {
    const res = await CreateHistoryGroup({
      group_title: 'chat room',
    }, {
      isLoading: isLoading
    });
 
    const newRoom = {
      id: res.history_group_id,
      isInitial: true,
      title: 'chat room',
    };
    if (!this.data.chatRoomList) {
      this.data.chatRoomList = [newRoom];
    } else {
      this.data.chatRoomList.unshift(newRoom);
    }
    this.setData({
      chatRoomList: this.data.chatRoomList
    })
    await this.setActiveChatRoom(newRoom);
  },
  async getHistoryGroupData() {
    const res = await GetHistoryGroups();
    const resData = (res?.groups || []) as any[];
 
    // 按最晚时间到最早时间
    this.data.chatRoomList = wx.$_.orderBy(resData, ['create_time'], ['desc'])
      .map((item) => {
        return {
          id: item.group_id,
          title: item.group_title,
          createTime: item.create_time,
          isInitial: Number(item.chat_count) === 0,
        };
      });
 
    if (!this.data.chatRoomList || this.data.chatRoomList.length === 0 || !this.data.chatRoomList?.[0].isInitial) {
      await this.newChatRoomClick(false);
    } else {
      this.setActiveChatRoom(this.data.chatRoomList[0]);
      this.setData(
        {
          chatRoomList: this.data.chatRoomList
        }
      )
    }
 
 
 
  },
  onSendTextChange: function (e) {
    // this.setData({
    //   sendText:e.detail.value
    // })
  },
  scrollToBottom() {
    wx.nextTick(() => {
      setTimeout(() => {
        this.setData({
          toViewId: `chat-item-${this.data.chatHistory.length - 1}`,
        })
      }, 300);
    })
 
  },
  async getHistoryDetail( ) {
 
    const res = await QueryHistoryDetail({
      history_group_id: this.data.activeChatRoom.id,
    });
    this.setData({
      chatHistory: (res.details ?? []).map((item) => {
        return {
          historyId: item.history_id,
          role: RoleEnum.user,
          content: {
            type: AnswerType.Text,
            values: item.question,
          },
        }
      })
    })
 
 
    // currentSampleId = res?.details?.[0]?.sample_id;
    const sectionAIdMap = new Map();
    const resList: any[] = await Promise.all((res.details ?? []).map((item) => {
      sectionAIdMap.set(item.history_id, item.section_a_id)
      return getAnswerById(item.history_id)
    }));
    let i = 0;
 
    resList.map((item, index) => {
      const insertIndex = index + 1 + i;
      this.data.chatHistory.splice(
        insertIndex,
        0,
        item.answer === null ?
          null :
          {
            historyId: item.answer?.history_id,
            role: RoleEnum.assistant,
            content: parseContent(item.answer),
            state: item.answer_state,
            sectionAId: sectionAIdMap.get(item.answer.history_id)
          }
      );
      i++;
    });
 
      // 过滤为null的结果
    this.setData({
      chatHistory: this.data.chatHistory.filter(item=>!!item)
    })
    this.scrollToBottom()
 
 
  },
 
  resetLastChatRoom() {
    const isInitial = this.data.activeChatRoom.isInitial;
    this.setData({
      sendText: isInitial ? '你是谁?' : '',
    })
  },
  async setActiveChatRoom(room) {
    if (!room) return;
    this.setData({
      activeChatRoom: room,
    })
    this.resetLastChatRoom();
    wx.setNavigationBarTitle({
      title: this.data.activeChatRoom.title
    })
    await this.getHistoryDetail();
  },
  async chatRoomClick(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      drawerIsShow: false,
    })
    this.setActiveChatRoom(item)
  },
  delChatRoomClick(e) {
    const id = e.currentTarget.dataset.item.id;
    wx.modal({
      content: '确定删除当前聊天室吗?'
    }).then(async (val) => {
      if (!val) return;
      const res = await DeleteHistoryGroups({
        history_group_id: id,
      });
      if (!res?.json_ok) return;
      const foundIndex = this.data.chatRoomList.findIndex((item) => item.id === id);
      this.data.chatRoomList.splice(foundIndex, 1);
      if (this.data.chatRoomList.length === 0) {
        await this.newChatRoomClick();
      } else {
        this.setActiveChatRoom(this.data.chatRoomList[0]);
        this.setData({
          chatRoomList: this.data.chatRoomList
        })
      }
 
    })
  },
 
  // 聊天室图标点击
  chatRoomListClick() {
    this.setData({
      drawerIsShow: true,
    })
  },
  drawerCloseClick() {
    this.setData({
      drawerIsShow: false,
    })
  },
  onLoad(option) {
    const isPassed = checkAuth();
    if (!isPassed) return;
    this.getHistoryGroupData();
    this.getSampleList();
  },
 
  async onRouteDone() {
    const sectionAId = app.globalData.sectionAId;
 
    if (!sectionAId) {
      return;
    }
    this.setData(
      {
        section_a_id:sectionAId
      }
    )
    if (!this.data.activeChatRoom.isInitial) {
      try {
      
        await this.newChatRoomClick(false)
      } finally {
        wx.hideLoading();
      }
    }
    this.setData({
      sendText: app.globalData.sectionB.section_title
    })
 
    this.sendText();
    app.globalData.sectionAId = '';
    app.globalData.sectionB = null;
  }
 
  // pageLifetimes: {
  //   show() {
  //     if (typeof this.getTabBar === 'function' &&
  //       this.getTabBar()) {
  //       this.getTabBar().setData({
  //         selected: 0
  //       })
  //     }
  //   }
  // }
 
 
 
})