File size: 2,065 Bytes
755dd12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as tencentcloud from 'tencentcloud-sdk-nodejs';
import { ClientConfig } from 'tencentcloud-sdk-nodejs/tencentcloud/common/interface';
import { Client } from 'tencentcloud-sdk-nodejs/tencentcloud/services/hunyuan/v20230901/hunyuan_client';
import { ChatStdResponse } from 'tencentcloud-sdk-nodejs/tencentcloud/services/hunyuan/v20230901/hunyuan_models';
import { BaseChat } from './base/base';
import { IChatInputMessage, IStreamHandler } from '../interface';
import { DefaultSystem } from '../utils/constant';

export class TencentChat implements BaseChat {
  private client: Client;
  public platform = 'tencent';

  constructor() {
    const key = process.env.TENCENT_KEY;
    const secret = process.env.TENCENT_SECRET;
    const config: ClientConfig = {
      credential: {
        secretId: key,
        secretKey: secret
      },
      region: '',
      profile: {
        httpProfile: {
          endpoint: 'hunyuan.tencentcloudapi.com'
        }
      }
    };
    this.client = new tencentcloud.hunyuan.v20230901.Client(config);
  }

  async chatStream(
    messages: IChatInputMessage[],
    onMessage: IStreamHandler,
    model: string,
    system = DefaultSystem
  ): Promise<void> {
    const Messages = this.transformMessage(messages);
    console.log(model);
    if (system) {
      Messages.unshift({
        Role: 'system',
        Content: system
      });
    }
    const result: any = await this.client.ChatStd({
      Messages
    });
    return new Promise((resolve) => {
      result.on('message', (res: any) => {
        const data: ChatStdResponse = JSON.parse(res.data ?? '{}');
        const text = data.Choices?.[0].Delta?.Content || '';
        const stop = data.Choices?.[0].FinishReason === 'stop' ? true : false;
        onMessage?.(text, stop);
        if (stop) resolve();
      });
    });
  }

  private transformMessage(messages: IChatInputMessage[]) {
    return messages.map(msg => {
      return {
        Role: msg.role,
        Content: msg.content
      };
    });
  }
}

export const tencent = new TencentChat();