import axios from 'axios' import { getAccessToken } from '../../get-access-token' import { ChatBotConstructorParams, ChatApiResponseBodyBase, ChatMessageBase, ChatParamsBase, ChatBotConfigBase } from './types' abstract class ChatBotBase< ChatMessage extends ChatMessageBase, ChatApiResponseBody extends ChatApiResponseBodyBase, ChatBotConfig extends Pick > { private apiKey: string private secretKey: string private accessToken: string private botConfig: ChatBotConfig protected abstract getDefaultConfig(): ChatBotConfig protected abstract getApiUrl():Promise protected async getAccessToken():Promise { if (!this.accessToken) { const accessTokenInfo = await getAccessToken({AK: this.apiKey, SK: this.secretKey}) this.accessToken = accessTokenInfo?.access_token } return this.accessToken } protected constructor(params: ChatBotConstructorParams) { const {AK: apiKey, SK: secretKey } = params this.apiKey = apiKey this.secretKey = secretKey this.botConfig = this.getDefaultConfig() } public config (params: ChatBotConfig): this { this.botConfig = { ...this.botConfig, ...params } return this } public async chat(params: ChatParamsBase & ChatBotConfig ): Promise { const { messages, ...config } = params const currentConfig: ChatBotConfig = { ...this.botConfig, ...config } const res = await axios.post( await this.getApiUrl(), { messages, }, { headers: { 'Content-Type': 'application/json' }, responseType: currentConfig.stream ? 'stream': 'json' } ) const {data} = res return data } } export { ChatBotBase }