Chat.swift 6.8 KB

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