123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- //
- // TSAIChatVM.swift
- // AIEmoji
- //
- // Created by 100Years on 2025/2/9.
- //
- import Alamofire
- let kAIErrorString = "Server is busy, please try again later".localized
- class TSAIChatVM {
- enum UIStype {
- case chat
- case history
- }
-
- lazy var dbAIChatList: TSDBAIChatList = {
- let dbAIChatList = TSDBAIChatList.getOneDB()
- return dbAIChatList
- }()
- var uiStyle:UIStype = UIStype.chat
- var streamRequest:DataStreamRequest?
-
- let kAIUser = TSChatUser(senderId: "000", displayName: "AI",idType: .aiRobot)
- let kUserSender = TSChatUser(senderId: "001", displayName: "001",idType: .user)
-
-
- //ai markDown 回答的string
- var AiMDString:String = ""
-
-
-
- init() {
- NotificationCenter.default.addObserver(self, selector: #selector(handleAIStopRespondNotification(_:)), name: .kAIStopRespondNotification, object: nil)
- }
-
- @objc func handleAIStopRespondNotification(_ notification: Notification) {
- // if let userInfo = notification.userInfo, let boolValue = userInfo[kIsAIAnswering] as? Bool {
- // }
- stopAiGenerate()
- }
-
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
- }
- //MARK: AI 聊天请求
- extension TSAIChatVM {
-
- func sendChatMessage(
- message:String,
- streamHandler:@escaping (String) -> Void,
- completion: @escaping (Any?, Error?) -> Void
- ) {
- let parameters: [String: String] = [
- "sessionId": dbAIChatList.sessionId,
- "message": message
- ]
- AiMDString = ""
- streamRequest = TSNetworkShared.postStream(urlType: .chat,parameters: parameters) {[weak self] string in
- guard let self = self else { return }
-
- if AiMDString.count == 0 {
- //{"code":500,"message":"Server Error"}
- //如果错误,基本都是第一条就返回结果了,这里需要做下 code 判断,来确定接口
- if let dataDict = string.jsonDict() , let code = dataDict["code"] {
- completion(nil,NSError(domain: dataDict.safeString(forKey: "message"), code: 0))
- return
- }
- }
-
- AiMDString = AiMDString + string
- streamHandler(string)
- } completion: { result in
- switch result {
- case .success(let data):
- completion(data,nil)
- case .failure(let error):
- if case Alamofire.AFError.explicitlyCancelled = error {//主动取消的
- completion("",nil)
- } else {
- completion(nil,error)
- }
- }
- }
- }
-
- func stopAiGenerate () {
- streamRequest?.cancel()
- }
- }
- //MARK: 数据存储
- extension TSAIChatVM {
-
- func getHistoryChatMessage() -> [TSChatMessage] {
- if uiStyle == .history {
- return self.dbAIChatList.getMessageList()
- }else {
- // let aiString = "I can tackle your questions, my skillset includes, but is not limited to:\n**📧 Composing high-quality emails**\n**🇺🇸 Facilitating language learning**\n**📑 Assisting in your studies**\n**💡Brainstorming ideas**\n**and much more!**"
- let aiString = "I can tackle your questions, my skillset includes, but is not limited to:\n`📧 Composing high-quality emails`\n`🇺🇸 Facilitating language learning`\n`📑 Assisting in your studies`\n`💡Brainstorming ideas`\n`and much more!`"
- let msg = TSChatMessage(kind: .attributedText(kMDAttributedString(text: aiString)), user: kAIUser, messageId: "", date: Date())
- let model = TSChatMessageUIBaseModel()
- model.height = 52.0
- model.view = TSMSGAIDefaultHeaderView(text: "Greetings! Curious about\nwhat I can do?".localized)
- msg.appendDict = [.topView:model]
- msg.messageType = .aiRobotWelcome
-
- return [msg]
- }
- }
-
- func updateMessages(msgModels:[TSChatMessage]){
- kExecuteOnMainThread {
- //保存数据库
- self.dbAIChatList.updateMessages(msgModels: msgModels)
- //保存服务器
- }
- }
- }
|