TemplateChatSession.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2025 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. // TODO: Restore `public` to class and methods when determined to be releaseable.
  16. /// A chat session that allows for conversation with a model.
  17. ///
  18. /// **Public Preview**: This API is a public preview and may be subject to change.
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. final class TemplateChatSession: Sendable {
  21. private let model: TemplateGenerativeModel
  22. private let templateID: String
  23. private let _history: History
  24. init(model: TemplateGenerativeModel, templateID: String, history: [ModelContent]) {
  25. self.model = model
  26. self.templateID = templateID
  27. _history = History(history: history)
  28. }
  29. public var history: [ModelContent] {
  30. get {
  31. return _history.history
  32. }
  33. set {
  34. _history.history = newValue
  35. }
  36. }
  37. /// Sends a message to the model and returns the response.
  38. ///
  39. /// **Public Preview**: This API is a public preview and may be subject to change.
  40. ///
  41. /// - Parameters:
  42. /// - content: The message to send to the model.
  43. /// - inputs: A dictionary of variables to substitute into the template.
  44. /// - options: The ``RequestOptions`` for the request, currently used to override default
  45. /// request timeout.
  46. /// - Returns: The content generated by the model.
  47. /// - Throws: A ``GenerateContentError`` if the request failed.
  48. func sendMessage(_ content: [ModelContent],
  49. inputs: [String: any TemplateInputRepresentable],
  50. options: RequestOptions = RequestOptions()) async throws
  51. -> GenerateContentResponse {
  52. let newContent = content.map(populateContentRole)
  53. let response = try await model.generateContentWithHistory(
  54. history: _history.history + newContent,
  55. template: templateID,
  56. inputs: inputs.mapValues { $0.templateInputRepresentation },
  57. options: options
  58. )
  59. _history.append(contentsOf: newContent)
  60. if let modelResponse = response.candidates.first {
  61. _history.append(modelResponse.content)
  62. }
  63. return response
  64. }
  65. /// Sends a message to the model and returns the response.
  66. ///
  67. /// **Public Preview**: This API is a public preview and may be subject to change.
  68. ///
  69. /// - Parameters:
  70. /// - message: The message to send to the model.
  71. /// - inputs: A dictionary of variables to substitute into the template.
  72. /// - options: The ``RequestOptions`` for the request, currently used to override default
  73. /// request timeout.
  74. /// - Returns: The content generated by the model.
  75. /// - Throws: A ``GenerateContentError`` if the request failed.
  76. func sendMessage(_ message: any PartsRepresentable,
  77. inputs: [String: any TemplateInputRepresentable],
  78. options: RequestOptions = RequestOptions()) async throws
  79. -> GenerateContentResponse {
  80. return try await sendMessage([ModelContent(parts: message.partsValue)],
  81. inputs: inputs,
  82. options: options)
  83. }
  84. /// Sends a message to the model and returns the response as a stream of
  85. /// `GenerateContentResponse`s.
  86. ///
  87. /// **Public Preview**: This API is a public preview and may be subject to change.
  88. ///
  89. /// - Parameters:
  90. /// - content: The message to send to the model.
  91. /// - inputs: A dictionary of variables to substitute into the template.
  92. /// - options: The ``RequestOptions`` for the request, currently used to override default
  93. /// request timeout.
  94. /// - Returns: An `AsyncThrowingStream` that yields `GenerateContentResponse` objects.
  95. /// - Throws: A ``GenerateContentError`` if the request failed.
  96. func sendMessageStream(_ content: [ModelContent],
  97. inputs: [String: any TemplateInputRepresentable],
  98. options: RequestOptions = RequestOptions()) throws
  99. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  100. let newContent = content.map(populateContentRole)
  101. let stream = try model.generateContentStreamWithHistory(
  102. history: _history.history + newContent,
  103. template: templateID,
  104. inputs: inputs.mapValues { $0.templateInputRepresentation },
  105. options: options
  106. )
  107. return AsyncThrowingStream { continuation in
  108. Task {
  109. var aggregatedContent: [ModelContent] = []
  110. do {
  111. for try await chunk in stream {
  112. // Capture any content that's streaming. This should be populated if there's no error.
  113. if let chunkContent = chunk.candidates.first?.content {
  114. aggregatedContent.append(chunkContent)
  115. }
  116. // Pass along the chunk.
  117. continuation.yield(chunk)
  118. }
  119. } catch {
  120. // Rethrow the error that the underlying stream threw. Don't add anything to history.
  121. continuation.finish(throwing: error)
  122. return
  123. }
  124. // Save the request.
  125. _history.append(contentsOf: newContent)
  126. // Aggregate the content to add it to the history before we finish.
  127. let aggregated = _history.aggregatedChunks(aggregatedContent)
  128. _history.append(aggregated)
  129. continuation.finish()
  130. }
  131. }
  132. }
  133. /// Sends a message to the model and returns the response as a stream of
  134. /// `GenerateContentResponse`s.
  135. ///
  136. /// **Public Preview**: This API is a public preview and may be subject to change.
  137. ///
  138. /// - Parameters:
  139. /// - message: The message to send to the model.
  140. /// - inputs: A dictionary of variables to substitute into the template.
  141. /// - options: The ``RequestOptions`` for the request, currently used to override default
  142. /// request timeout.
  143. /// - Returns: An `AsyncThrowingStream` that yields `GenerateContentResponse` objects.
  144. /// - Throws: A ``GenerateContentError`` if the request failed.
  145. func sendMessageStream(_ message: any PartsRepresentable,
  146. inputs: [String: any TemplateInputRepresentable],
  147. options: RequestOptions = RequestOptions()) throws
  148. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  149. return try sendMessageStream([ModelContent(parts: message.partsValue)],
  150. inputs: inputs,
  151. options: options)
  152. }
  153. private func populateContentRole(_ content: ModelContent) -> ModelContent {
  154. if content.role != nil {
  155. return content
  156. } else {
  157. return ModelContent(role: "user", parts: content.parts)
  158. }
  159. }
  160. }