Chat.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 Foundation
  15. /// An object that represents a back-and-forth chat with a model, capturing the history and saving
  16. /// the context in memory between each message sent.
  17. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  18. public final class Chat: Sendable {
  19. private let model: GenerativeModel
  20. /// Initializes a new chat representing a 1:1 conversation between model and user.
  21. init(model: GenerativeModel, history: [ModelContent]) {
  22. self.model = model
  23. self.history = history
  24. }
  25. private let historyLock = NSLock()
  26. private nonisolated(unsafe) var _history: [ModelContent] = []
  27. /// The previous content from the chat that has been successfully sent and received from the
  28. /// model. This will be provided to the model for each message sent as context for the discussion.
  29. public var history: [ModelContent] {
  30. get {
  31. historyLock.withLock { _history }
  32. }
  33. set {
  34. historyLock.withLock { _history = newValue }
  35. }
  36. }
  37. private func appendHistory(contentsOf: [ModelContent]) {
  38. historyLock.withLock {
  39. _history.append(contentsOf: contentsOf)
  40. }
  41. }
  42. /// Sends a message using the existing history of this chat as context. If successful, the message
  43. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  44. /// - Parameter parts: The new content to send as a single chat message.
  45. /// - Returns: The model's response if no error occurred.
  46. /// - Throws: A ``GenerateContentError`` if an error occurred.
  47. public func sendMessage(_ parts: any PartsRepresentable...) async throws
  48. -> GenerateContentResponse {
  49. return try await sendMessage([ModelContent(parts: parts)])
  50. }
  51. /// Sends a message using the existing history of this chat as context. If successful, the message
  52. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  53. /// - Parameter content: The new content to send as a single chat message.
  54. /// - Returns: The model's response if no error occurred.
  55. /// - Throws: A ``GenerateContentError`` if an error occurred.
  56. public func sendMessage(_ content: [ModelContent]) async throws
  57. -> GenerateContentResponse {
  58. // Ensure that the new content has the role set.
  59. let newContent = content.map(populateContentRole(_:))
  60. // Send the history alongside the new message as context.
  61. let request = history + newContent
  62. let result = try await model.generateContent(request)
  63. guard let reply = result.candidates.first?.content else {
  64. let error = NSError(domain: "com.google.generative-ai",
  65. code: -1,
  66. userInfo: [
  67. NSLocalizedDescriptionKey: "No candidates with content available.",
  68. ])
  69. throw GenerateContentError.internalError(underlying: error)
  70. }
  71. // Make sure we inject the role into the content received.
  72. let toAdd = ModelContent(role: "model", parts: reply.parts)
  73. // Append the request and successful result to history, then return the value.
  74. appendHistory(contentsOf: newContent)
  75. history.append(toAdd)
  76. return result
  77. }
  78. /// Sends a message using the existing history of this chat as context. If successful, the message
  79. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  80. /// - Parameter parts: The new content to send as a single chat message.
  81. /// - Returns: A stream containing the model's response or an error if an error occurred.
  82. @available(macOS 12.0, *)
  83. public func sendMessageStream(_ parts: any PartsRepresentable...) throws
  84. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  85. return try sendMessageStream([ModelContent(parts: parts)])
  86. }
  87. /// Sends a message using the existing history of this chat as context. If successful, the message
  88. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  89. /// - Parameter content: The new content to send as a single chat message.
  90. /// - Returns: A stream containing the model's response or an error if an error occurred.
  91. @available(macOS 12.0, *)
  92. public func sendMessageStream(_ content: [ModelContent]) throws
  93. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  94. // Ensure that the new content has the role set.
  95. let newContent: [ModelContent] = content.map(populateContentRole(_:))
  96. // Send the history alongside the new message as context.
  97. let request = history + newContent
  98. let stream = try model.generateContentStream(request)
  99. return AsyncThrowingStream { continuation in
  100. Task {
  101. var aggregatedContent: [ModelContent] = []
  102. do {
  103. for try await chunk in stream {
  104. // Capture any content that's streaming. This should be populated if there's no error.
  105. if let chunkContent = chunk.candidates.first?.content {
  106. aggregatedContent.append(chunkContent)
  107. }
  108. // Pass along the chunk.
  109. continuation.yield(chunk)
  110. }
  111. } catch {
  112. // Rethrow the error that the underlying stream threw. Don't add anything to history.
  113. continuation.finish(throwing: error)
  114. return
  115. }
  116. // Save the request.
  117. appendHistory(contentsOf: newContent)
  118. // Aggregate the content to add it to the history before we finish.
  119. let aggregated = self.aggregatedChunks(aggregatedContent)
  120. self.history.append(aggregated)
  121. continuation.finish()
  122. }
  123. }
  124. }
  125. private func aggregatedChunks(_ chunks: [ModelContent]) -> ModelContent {
  126. var parts: [any Part] = []
  127. var combinedText = ""
  128. for aggregate in chunks {
  129. // Loop through all the parts, aggregating the text and adding the images.
  130. for part in aggregate.parts {
  131. switch part {
  132. case let textPart as TextPart:
  133. combinedText += textPart.text
  134. default:
  135. // Don't combine it, just add to the content. If there's any text pending, add that as
  136. // a part.
  137. if !combinedText.isEmpty {
  138. parts.append(TextPart(combinedText))
  139. combinedText = ""
  140. }
  141. parts.append(part)
  142. }
  143. }
  144. }
  145. if !combinedText.isEmpty {
  146. parts.append(TextPart(combinedText))
  147. }
  148. return ModelContent(role: "model", parts: parts)
  149. }
  150. /// Populates the `role` field with `user` if it doesn't exist. Required in chat sessions.
  151. private func populateContentRole(_ content: ModelContent) -> ModelContent {
  152. if content.role != nil {
  153. return content
  154. } else {
  155. return ModelContent(role: "user", parts: content.parts)
  156. }
  157. }
  158. }