GenerativeAIService.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseCore
  17. import Foundation
  18. import os.log
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. struct GenerativeAIService {
  21. /// The language of the SDK in the format `gl-<language>/<version>`.
  22. static let languageTag = "gl-swift/5"
  23. /// The Firebase SDK version in the format `fire/<version>`.
  24. static let firebaseVersionTag = "fire/\(FirebaseVersion())"
  25. private let firebaseInfo: FirebaseInfo
  26. private let urlSession: URLSession
  27. init(firebaseInfo: FirebaseInfo, urlSession: URLSession) {
  28. self.firebaseInfo = firebaseInfo
  29. self.urlSession = urlSession
  30. }
  31. func loadRequest<T: GenerativeAIRequest>(request: T) async throws -> T.Response {
  32. let urlRequest = try await urlRequest(request: request)
  33. #if DEBUG
  34. printCURLCommand(from: urlRequest)
  35. #endif
  36. let data: Data
  37. let rawResponse: URLResponse
  38. (data, rawResponse) = try await urlSession.data(for: urlRequest)
  39. let response = try httpResponse(urlResponse: rawResponse)
  40. // Verify the status code is 200
  41. guard response.statusCode == 200 else {
  42. AILog.error(
  43. code: .loadRequestResponseError,
  44. "The server responded with an error: \(response)"
  45. )
  46. if let responseString = String(data: data, encoding: .utf8) {
  47. AILog.error(
  48. code: .loadRequestResponseErrorPayload,
  49. "Response payload: \(responseString)"
  50. )
  51. }
  52. throw parseError(responseData: data)
  53. }
  54. return try parseResponse(T.Response.self, from: data)
  55. }
  56. @available(macOS 12.0, *)
  57. func loadRequestStream<T: GenerativeAIRequest>(request: T)
  58. -> AsyncThrowingStream<T.Response, Error> where T: Sendable {
  59. return AsyncThrowingStream { continuation in
  60. Task {
  61. let urlRequest: URLRequest
  62. do {
  63. urlRequest = try await self.urlRequest(request: request)
  64. } catch {
  65. continuation.finish(throwing: error)
  66. return
  67. }
  68. #if DEBUG
  69. printCURLCommand(from: urlRequest)
  70. #endif
  71. let stream: URLSession.AsyncBytes
  72. let rawResponse: URLResponse
  73. do {
  74. (stream, rawResponse) = try await urlSession.bytes(for: urlRequest)
  75. } catch {
  76. continuation.finish(throwing: error)
  77. return
  78. }
  79. // Verify the status code is 200
  80. let response: HTTPURLResponse
  81. do {
  82. response = try httpResponse(urlResponse: rawResponse)
  83. } catch {
  84. continuation.finish(throwing: error)
  85. return
  86. }
  87. // Verify the status code is 200
  88. guard response.statusCode == 200 else {
  89. AILog.error(
  90. code: .loadRequestStreamResponseError,
  91. "The server responded with an error: \(response)"
  92. )
  93. var responseBody = ""
  94. for try await line in stream.lines {
  95. responseBody += line + "\n"
  96. }
  97. AILog.error(
  98. code: .loadRequestStreamResponseErrorPayload,
  99. "Response payload: \(responseBody)"
  100. )
  101. continuation.finish(throwing: parseError(responseBody: responseBody))
  102. return
  103. }
  104. // Received lines that are not server-sent events (SSE); these are not prefixed with "data:"
  105. var extraLines = ""
  106. let decoder = JSONDecoder()
  107. decoder.keyDecodingStrategy = .convertFromSnakeCase
  108. for try await line in stream.lines {
  109. AILog.debug(code: .loadRequestStreamResponseLine, "Stream response: \(line)")
  110. if line.hasPrefix("data:") {
  111. // We can assume 5 characters since it's utf-8 encoded, removing `data:`.
  112. let jsonText = String(line.dropFirst(5))
  113. let data: Data
  114. do {
  115. data = try jsonData(jsonText: jsonText)
  116. } catch {
  117. continuation.finish(throwing: error)
  118. return
  119. }
  120. // Handle the content.
  121. do {
  122. let content = try parseResponse(T.Response.self, from: data)
  123. continuation.yield(content)
  124. } catch {
  125. continuation.finish(throwing: error)
  126. return
  127. }
  128. } else {
  129. extraLines += line
  130. }
  131. }
  132. if extraLines.count > 0 {
  133. continuation.finish(throwing: parseError(responseBody: extraLines))
  134. return
  135. }
  136. continuation.finish(throwing: nil)
  137. }
  138. }
  139. }
  140. // MARK: - Private Helpers
  141. private func urlRequest<T: GenerativeAIRequest>(request: T) async throws -> URLRequest {
  142. var urlRequest = URLRequest(url: request.url)
  143. urlRequest.httpMethod = "POST"
  144. urlRequest.setValue(firebaseInfo.apiKey, forHTTPHeaderField: "x-goog-api-key")
  145. urlRequest.setValue(
  146. "\(GenerativeAIService.languageTag) \(GenerativeAIService.firebaseVersionTag)",
  147. forHTTPHeaderField: "x-goog-api-client"
  148. )
  149. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  150. if let appCheck = firebaseInfo.appCheck {
  151. let tokenResult = await appCheck.getToken(forcingRefresh: false)
  152. urlRequest.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  153. if let error = tokenResult.error {
  154. AILog.error(
  155. code: .appCheckTokenFetchFailed,
  156. "Failed to fetch AppCheck token. Error: \(error)"
  157. )
  158. }
  159. }
  160. if let auth = firebaseInfo.auth, let authToken = try await auth.getToken(
  161. forcingRefresh: false
  162. ) {
  163. urlRequest.setValue("Firebase \(authToken)", forHTTPHeaderField: "Authorization")
  164. }
  165. if firebaseInfo.app.isDataCollectionDefaultEnabled {
  166. urlRequest.setValue(firebaseInfo.firebaseAppID, forHTTPHeaderField: "X-Firebase-AppId")
  167. if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
  168. urlRequest.setValue(appVersion, forHTTPHeaderField: "X-Firebase-AppVersion")
  169. }
  170. }
  171. let encoder = JSONEncoder()
  172. urlRequest.httpBody = try encoder.encode(request)
  173. urlRequest.timeoutInterval = request.options.timeout
  174. return urlRequest
  175. }
  176. private func httpResponse(urlResponse: URLResponse) throws -> HTTPURLResponse {
  177. // The following condition should always be true: "Whenever you make HTTP URL load requests, any
  178. // response objects you get back from the URLSession, NSURLConnection, or NSURLDownload class
  179. // are instances of the HTTPURLResponse class."
  180. guard let response = urlResponse as? HTTPURLResponse else {
  181. AILog.error(
  182. code: .generativeAIServiceNonHTTPResponse,
  183. "Response wasn't an HTTP response, internal error \(urlResponse)"
  184. )
  185. throw URLError(
  186. .badServerResponse,
  187. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  188. )
  189. }
  190. return response
  191. }
  192. private func jsonData(jsonText: String) throws -> Data {
  193. guard let data = jsonText.data(using: .utf8) else {
  194. throw DecodingError.dataCorrupted(DecodingError.Context(
  195. codingPath: [],
  196. debugDescription: "Could not parse response as UTF8."
  197. ))
  198. }
  199. return data
  200. }
  201. private func parseError(responseBody: String) -> Error {
  202. do {
  203. let data = try jsonData(jsonText: responseBody)
  204. return parseError(responseData: data)
  205. } catch {
  206. return error
  207. }
  208. }
  209. private func parseError(responseData: Data) -> Error {
  210. do {
  211. let rpcError = try JSONDecoder().decode(BackendError.self, from: responseData)
  212. logRPCError(rpcError)
  213. return rpcError
  214. } catch {
  215. // TODO: Return an error about an unrecognized error payload with the response body
  216. return error
  217. }
  218. }
  219. // Log specific RPC errors that cannot be mitigated or handled by user code.
  220. // These errors do not produce specific GenerateContentError or CountTokensError cases.
  221. private func logRPCError(_ error: BackendError) {
  222. let projectID = firebaseInfo.projectID
  223. if error.isVertexAIInFirebaseServiceDisabledError() {
  224. AILog.error(code: .vertexAIInFirebaseAPIDisabled, """
  225. The Firebase AI SDK requires the Firebase AI API \
  226. (`firebasevertexai.googleapis.com`) to be enabled in your Firebase project. Enable this API \
  227. by visiting the Firebase Console at
  228. https://console.firebase.google.com/project/\(projectID)/genai/ and clicking "Get started". \
  229. If you enabled this API recently, wait a few minutes for the action to propagate to our \
  230. systems and then retry.
  231. """)
  232. }
  233. }
  234. private func parseResponse<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
  235. do {
  236. return try JSONDecoder().decode(type, from: data)
  237. } catch {
  238. if let json = String(data: data, encoding: .utf8) {
  239. AILog.error(code: .loadRequestParseResponseFailedJSON, "JSON response: \(json)")
  240. }
  241. AILog.error(
  242. code: .loadRequestParseResponseFailedJSONError,
  243. "Error decoding server JSON: \(error)"
  244. )
  245. throw error
  246. }
  247. }
  248. #if DEBUG
  249. private func cURLCommand(from request: URLRequest) -> String {
  250. var returnValue = "curl "
  251. if let allHeaders = request.allHTTPHeaderFields {
  252. for (key, value) in allHeaders {
  253. returnValue += "-H '\(key): \(value)' "
  254. }
  255. }
  256. guard let url = request.url else { return "" }
  257. returnValue += "'\(url.absoluteString)' "
  258. guard let body = request.httpBody,
  259. let jsonStr = String(bytes: body, encoding: .utf8) else { return "" }
  260. let escapedJSON = jsonStr.replacingOccurrences(of: "'", with: "'\\''")
  261. returnValue += "-d '\(escapedJSON)'"
  262. return returnValue
  263. }
  264. private func printCURLCommand(from request: URLRequest) {
  265. guard AILog.additionalLoggingEnabled() else {
  266. return
  267. }
  268. let command = cURLCommand(from: request)
  269. os_log(.debug, log: AILog.logObject, """
  270. \(AILog.service) Creating request with the equivalent cURL command:
  271. ----- cURL command -----
  272. \(command, privacy: .private)
  273. ------------------------
  274. """)
  275. }
  276. #endif // DEBUG
  277. }