FunctionCallingViewModel.swift 8.6 KB

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