ConversationViewModel.swift 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseVertexAI
  15. import Foundation
  16. import UIKit
  17. @MainActor
  18. class ConversationViewModel: ObservableObject {
  19. /// This array holds both the user's and the system's chat messages
  20. @Published var messages = [ChatMessage]()
  21. /// Indicates we're waiting for the model to finish or the UI is loading
  22. @Published var busy = true
  23. @Published var error: Error?
  24. var hasError: Bool {
  25. return error != nil
  26. }
  27. private var model: GenerativeModel
  28. private var chat: Chat? = nil
  29. private var stopGenerating = false
  30. private var chatTask: Task<Void, Never>?
  31. init() {
  32. model = VertexAI.vertexAI().generativeModel(modelName: "gemini-1.5-flash")
  33. Task {
  34. await startNewChat()
  35. }
  36. }
  37. func sendMessage(_ text: String, streaming: Bool = true) async {
  38. stop()
  39. if streaming {
  40. await internalSendMessageStreaming(text)
  41. } else {
  42. await internalSendMessage(text)
  43. }
  44. }
  45. func startNewChat() async {
  46. busy = true
  47. defer {
  48. busy = false
  49. }
  50. stop()
  51. messages.removeAll()
  52. chat = await model.startChat()
  53. }
  54. func stop() {
  55. chatTask?.cancel()
  56. error = nil
  57. }
  58. private func internalSendMessageStreaming(_ text: String) async {
  59. chatTask = Task {
  60. busy = true
  61. defer {
  62. busy = false
  63. }
  64. // first, add the user's message to the chat
  65. let userMessage = ChatMessage(message: text, participant: .user)
  66. messages.append(userMessage)
  67. // add a pending message while we're waiting for a response from the backend
  68. let systemMessage = ChatMessage.pending(participant: .system)
  69. messages.append(systemMessage)
  70. do {
  71. guard let chat else {
  72. throw ChatError.notInitialized
  73. }
  74. let responseStream = try await chat.sendMessageStream(text)
  75. for try await chunk in responseStream {
  76. messages[messages.count - 1].pending = false
  77. if let text = chunk.text {
  78. messages[messages.count - 1].message += text
  79. }
  80. }
  81. } catch {
  82. self.error = error
  83. print(error.localizedDescription)
  84. messages.removeLast()
  85. }
  86. }
  87. }
  88. private func internalSendMessage(_ text: String) async {
  89. chatTask = Task {
  90. busy = true
  91. defer {
  92. busy = false
  93. }
  94. // first, add the user's message to the chat
  95. let userMessage = ChatMessage(message: text, participant: .user)
  96. messages.append(userMessage)
  97. // add a pending message while we're waiting for a response from the backend
  98. let systemMessage = ChatMessage.pending(participant: .system)
  99. messages.append(systemMessage)
  100. do {
  101. guard let chat = chat else {
  102. throw ChatError.notInitialized
  103. }
  104. let response = try await chat.sendMessage(text)
  105. if let responseText = response.text {
  106. // replace pending message with backend response
  107. messages[messages.count - 1].message = responseText
  108. messages[messages.count - 1].pending = false
  109. }
  110. } catch {
  111. self.error = error
  112. print(error.localizedDescription)
  113. messages.removeLast()
  114. }
  115. }
  116. }
  117. enum ChatError: Error {
  118. case notInitialized
  119. }
  120. }