SummarizeViewModel.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 OSLog
  17. @MainActor
  18. class SummarizeViewModel: ObservableObject {
  19. private var logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "generative-ai")
  20. @Published
  21. var outputText = ""
  22. @Published
  23. var errorMessage: String?
  24. @Published
  25. var inProgress = false
  26. private var model: GenerativeModel?
  27. init() {
  28. model = VertexAI.vertexAI().generativeModel(modelName: "gemini-1.5-flash-preview-0514")
  29. }
  30. func summarize(inputText: String) async {
  31. defer {
  32. inProgress = false
  33. }
  34. guard let model else {
  35. return
  36. }
  37. do {
  38. inProgress = true
  39. errorMessage = nil
  40. outputText = ""
  41. let prompt = "Summarize the following text for me: \(inputText)"
  42. let outputContentStream = model.generateContentStream(prompt)
  43. // stream response
  44. for try await outputContent in outputContentStream {
  45. guard let line = outputContent.text else {
  46. return
  47. }
  48. outputText = outputText + line
  49. }
  50. } catch {
  51. logger.error("\(error.localizedDescription)")
  52. errorMessage = error.localizedDescription
  53. }
  54. }
  55. }