TSAIChatVM.swift 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. //
  2. // TSAIChatVM.swift
  3. // AIEmoji
  4. //
  5. // Created by 100Years on 2025/2/9.
  6. //
  7. import Alamofire
  8. let kAIErrorString = "Server is busy, please try again later".localized
  9. class TSAIChatVM {
  10. enum UIStype {
  11. case chat
  12. case history
  13. }
  14. lazy var dbAIChatList: TSDBAIChatList = {
  15. let dbAIChatList = TSDBAIChatList.getOneDB()
  16. return dbAIChatList
  17. }()
  18. var uiStyle:UIStype = UIStype.chat
  19. var streamRequest:DataStreamRequest?
  20. let kAIUser = TSChatUser(senderId: "000", displayName: "AI",idType: .aiRobot)
  21. let kUserSender = TSChatUser(senderId: "001", displayName: "001",idType: .user)
  22. //ai markDown 回答的string
  23. var AiMDString:String = ""
  24. init() {
  25. NotificationCenter.default.addObserver(self, selector: #selector(handleAIStopRespondNotification(_:)), name: .kAIStopRespondNotification, object: nil)
  26. }
  27. @objc func handleAIStopRespondNotification(_ notification: Notification) {
  28. // if let userInfo = notification.userInfo, let boolValue = userInfo[kIsAIAnswering] as? Bool {
  29. // }
  30. stopAiGenerate()
  31. }
  32. deinit {
  33. NotificationCenter.default.removeObserver(self)
  34. }
  35. }
  36. //MARK: AI 聊天请求
  37. extension TSAIChatVM {
  38. func sendChatMessage(
  39. message:String,
  40. streamHandler:@escaping (String) -> Void,
  41. completion: @escaping (Any?, Error?) -> Void
  42. ) {
  43. let parameters: [String: String] = [
  44. "sessionId": dbAIChatList.sessionId,
  45. "message": message
  46. ]
  47. AiMDString = ""
  48. streamRequest = TSNetworkShared.postStream(urlType: .chat,parameters: parameters) {[weak self] string in
  49. guard let self = self else { return }
  50. if AiMDString.count == 0 {
  51. //{"code":500,"message":"Server Error"}
  52. //如果错误,基本都是第一条就返回结果了,这里需要做下 code 判断,来确定接口
  53. if let dataDict = string.jsonDict() , let code = dataDict["code"] {
  54. completion(nil,NSError(domain: dataDict.safeString(forKey: "message"), code: 0))
  55. return
  56. }
  57. }
  58. AiMDString = AiMDString + string
  59. streamHandler(string)
  60. } completion: { result in
  61. switch result {
  62. case .success(let data):
  63. completion(data,nil)
  64. case .failure(let error):
  65. if case Alamofire.AFError.explicitlyCancelled = error {//主动取消的
  66. completion("",nil)
  67. } else {
  68. completion(nil,error)
  69. }
  70. }
  71. }
  72. }
  73. func stopAiGenerate () {
  74. streamRequest?.cancel()
  75. }
  76. }
  77. //MARK: 数据存储
  78. extension TSAIChatVM {
  79. func getHistoryChatMessage() -> [TSChatMessage] {
  80. if uiStyle == .history {
  81. return self.dbAIChatList.getMessageList()
  82. }else {
  83. // 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!**"
  84. 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!`"
  85. let msg = TSChatMessage(kind: .attributedText(kMDAttributedString(text: aiString)), user: kAIUser, messageId: "", date: Date())
  86. let model = TSChatMessageUIBaseModel()
  87. model.height = 52.0
  88. model.view = TSMSGAIDefaultHeaderView(text: "Greetings! Curious about\nwhat I can do?".localized)
  89. msg.appendDict = [.topView:model]
  90. msg.messageType = .aiRobotWelcome
  91. return [msg]
  92. }
  93. }
  94. func updateMessages(msgModels:[TSChatMessage]){
  95. kExecuteOnMainThread {
  96. //保存数据库
  97. self.dbAIChatList.updateMessages(msgModels: msgModels)
  98. //保存服务器
  99. }
  100. }
  101. }