FunctionCallingViewModel.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 FunctionCallingViewModel: 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
  22. @Published var busy = false
  23. @Published var error: Error?
  24. var hasError: Bool {
  25. return error != nil
  26. }
  27. /// Function calls pending processing
  28. private var functionCalls = [FunctionCall]()
  29. private var model: GenerativeModel
  30. private var chat: Chat
  31. private var chatTask: Task<Void, Never>?
  32. init() {
  33. model = VertexAI.vertexAI().generativeModel(
  34. modelName: "gemini-1.5-flash-preview-0514",
  35. tools: [Tool(functionDeclarations: [
  36. FunctionDeclaration(
  37. name: "get_exchange_rate",
  38. description: "Get the exchange rate for currencies between countries",
  39. parameters: [
  40. "currency_from": Schema(
  41. type: .string,
  42. format: "enum",
  43. description: "The currency to convert from in ISO 4217 format",
  44. enumValues: ["USD", "EUR", "JPY", "GBP", "AUD", "CAD"]
  45. ),
  46. "currency_to": Schema(
  47. type: .string,
  48. format: "enum",
  49. description: "The currency to convert to in ISO 4217 format",
  50. enumValues: ["USD", "EUR", "JPY", "GBP", "AUD", "CAD"]
  51. ),
  52. ],
  53. requiredParameters: ["currency_from", "currency_to"]
  54. ),
  55. ])]
  56. )
  57. chat = model.startChat()
  58. }
  59. func sendMessage(_ text: String, streaming: Bool = true) async {
  60. error = nil
  61. chatTask?.cancel()
  62. chatTask = Task {
  63. busy = true
  64. defer {
  65. busy = false
  66. }
  67. // first, add the user's message to the chat
  68. let userMessage = ChatMessage(message: text, participant: .user)
  69. messages.append(userMessage)
  70. // add a pending message while we're waiting for a response from the backend
  71. let systemMessage = ChatMessage.pending(participant: .system)
  72. messages.append(systemMessage)
  73. print(messages)
  74. do {
  75. repeat {
  76. if streaming {
  77. try await internalSendMessageStreaming(text)
  78. } else {
  79. try await internalSendMessage(text)
  80. }
  81. } while !functionCalls.isEmpty
  82. } catch {
  83. self.error = error
  84. print(error.localizedDescription)
  85. messages.removeLast()
  86. }
  87. }
  88. }
  89. func startNewChat() {
  90. stop()
  91. error = nil
  92. chat = model.startChat()
  93. messages.removeAll()
  94. }
  95. func stop() {
  96. chatTask?.cancel()
  97. error = nil
  98. }
  99. private func internalSendMessageStreaming(_ text: String) async throws {
  100. let functionResponses = try await processFunctionCalls()
  101. let responseStream: AsyncThrowingStream<GenerateContentResponse, Error>
  102. if functionResponses.isEmpty {
  103. responseStream = chat.sendMessageStream(text)
  104. } else {
  105. for functionResponse in functionResponses {
  106. messages.insert(functionResponse.chatMessage(), at: messages.count - 1)
  107. }
  108. responseStream = chat.sendMessageStream(functionResponses.modelContent())
  109. }
  110. for try await chunk in responseStream {
  111. processResponseContent(content: chunk)
  112. }
  113. }
  114. private func internalSendMessage(_ text: String) async throws {
  115. let functionResponses = try await processFunctionCalls()
  116. let response: GenerateContentResponse
  117. if functionResponses.isEmpty {
  118. response = try await chat.sendMessage(text)
  119. } else {
  120. for functionResponse in functionResponses {
  121. messages.insert(functionResponse.chatMessage(), at: messages.count - 1)
  122. }
  123. response = try await chat.sendMessage(functionResponses.modelContent())
  124. }
  125. processResponseContent(content: response)
  126. }
  127. func processResponseContent(content: GenerateContentResponse) {
  128. guard let candidate = content.candidates.first else {
  129. fatalError("No candidate.")
  130. }
  131. for part in candidate.content.parts {
  132. switch part {
  133. case let .text(text):
  134. // replace pending message with backend response
  135. messages[messages.count - 1].message += text
  136. messages[messages.count - 1].pending = false
  137. case let .functionCall(functionCall):
  138. messages.insert(functionCall.chatMessage(), at: messages.count - 1)
  139. functionCalls.append(functionCall)
  140. case .data, .fileData, .functionResponse:
  141. fatalError("Unsupported response content.")
  142. }
  143. }
  144. }
  145. func processFunctionCalls() async throws -> [FunctionResponse] {
  146. var functionResponses = [FunctionResponse]()
  147. for functionCall in functionCalls {
  148. switch functionCall.name {
  149. case "get_exchange_rate":
  150. let exchangeRates = getExchangeRate(args: functionCall.args)
  151. functionResponses.append(FunctionResponse(
  152. name: "get_exchange_rate",
  153. response: exchangeRates
  154. ))
  155. default:
  156. fatalError("Unknown function named \"\(functionCall.name)\".")
  157. }
  158. }
  159. functionCalls = []
  160. return functionResponses
  161. }
  162. // MARK: - Callable Functions
  163. func getExchangeRate(args: JSONObject) -> JSONObject {
  164. // 1. Validate and extract the parameters provided by the model (from a `FunctionCall`)
  165. guard case let .string(from) = args["currency_from"] else {
  166. fatalError("Missing `currency_from` parameter.")
  167. }
  168. guard case let .string(to) = args["currency_to"] else {
  169. fatalError("Missing `currency_to` parameter.")
  170. }
  171. // 2. Get the exchange rate
  172. let allRates: [String: [String: Double]] = [
  173. "AUD": ["CAD": 0.89265, "EUR": 0.6072, "GBP": 0.51714, "JPY": 97.75, "USD": 0.66379],
  174. "CAD": ["AUD": 1.1203, "EUR": 0.68023, "GBP": 0.57933, "JPY": 109.51, "USD": 0.74362],
  175. "EUR": ["AUD": 1.6469, "CAD": 1.4701, "GBP": 0.85168, "JPY": 160.99, "USD": 1.0932],
  176. "GBP": ["AUD": 1.9337, "CAD": 1.7261, "EUR": 1.1741, "JPY": 189.03, "USD": 1.2836],
  177. "JPY": ["AUD": 0.01023, "CAD": 0.00913, "EUR": 0.00621, "GBP": 0.00529, "USD": 0.00679],
  178. "USD": ["AUD": 1.5065, "CAD": 1.3448, "EUR": 0.91475, "GBP": 0.77907, "JPY": 147.26],
  179. ]
  180. guard let fromRates = allRates[from] else {
  181. return ["error": .string("No data for currency \(from).")]
  182. }
  183. guard let toRate = fromRates[to] else {
  184. return ["error": .string("No data for currency \(to).")]
  185. }
  186. // 3. Return the exchange rates as a JSON object (returned to the model in a `FunctionResponse`)
  187. return ["rates": .number(toRate)]
  188. }
  189. }
  190. private extension FunctionCall {
  191. func chatMessage() -> ChatMessage {
  192. let encoder = JSONEncoder()
  193. encoder.outputFormatting = .prettyPrinted
  194. let jsonData: Data
  195. do {
  196. jsonData = try encoder.encode(self)
  197. } catch {
  198. fatalError("JSON Encoding Failed: \(error.localizedDescription)")
  199. }
  200. guard let json = String(data: jsonData, encoding: .utf8) else {
  201. fatalError("Failed to convert JSON data to a String.")
  202. }
  203. let messageText = "Function call requested by model:\n```\n\(json)\n```"
  204. return ChatMessage(message: messageText, participant: .system)
  205. }
  206. }
  207. private extension FunctionResponse {
  208. func chatMessage() -> ChatMessage {
  209. let encoder = JSONEncoder()
  210. encoder.outputFormatting = .prettyPrinted
  211. let jsonData: Data
  212. do {
  213. jsonData = try encoder.encode(self)
  214. } catch {
  215. fatalError("JSON Encoding Failed: \(error.localizedDescription)")
  216. }
  217. guard let json = String(data: jsonData, encoding: .utf8) else {
  218. fatalError("Failed to convert JSON data to a String.")
  219. }
  220. let messageText = "Function response returned by app:\n```\n\(json)\n```"
  221. return ChatMessage(message: messageText, participant: .user)
  222. }
  223. }
  224. private extension [FunctionResponse] {
  225. func modelContent() -> [ModelContent] {
  226. return self.map { ModelContent(
  227. role: "function",
  228. parts: [ModelContent.Part.functionResponse($0)]
  229. )
  230. }
  231. }
  232. }