GenerativeAIService.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. 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 = try URLRequest(url: request.getURL())
  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 = try await appCheck.fetchAppCheckToken(
  152. limitedUse: firebaseInfo.useLimitedUseAppCheckTokens,
  153. domain: "GenerativeAIService"
  154. )
  155. urlRequest.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  156. if let error = tokenResult.error {
  157. AILog.error(
  158. code: .appCheckTokenFetchFailed,
  159. "Failed to fetch AppCheck token. Error: \(error)"
  160. )
  161. }
  162. }
  163. if let auth = firebaseInfo.auth, let authToken = try await auth.getToken(
  164. forcingRefresh: false
  165. ) {
  166. urlRequest.setValue("Firebase \(authToken)", forHTTPHeaderField: "Authorization")
  167. }
  168. if firebaseInfo.app.isDataCollectionDefaultEnabled {
  169. urlRequest.setValue(firebaseInfo.firebaseAppID, forHTTPHeaderField: "X-Firebase-AppId")
  170. if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
  171. urlRequest.setValue(appVersion, forHTTPHeaderField: "X-Firebase-AppVersion")
  172. }
  173. }
  174. let encoder = JSONEncoder()
  175. urlRequest.httpBody = try encoder.encode(request)
  176. urlRequest.timeoutInterval = request.options.timeout
  177. return urlRequest
  178. }
  179. private func httpResponse(urlResponse: URLResponse) throws -> HTTPURLResponse {
  180. // The following condition should always be true: "Whenever you make HTTP URL load requests, any
  181. // response objects you get back from the URLSession, NSURLConnection, or NSURLDownload class
  182. // are instances of the HTTPURLResponse class."
  183. guard let response = urlResponse as? HTTPURLResponse else {
  184. AILog.error(
  185. code: .generativeAIServiceNonHTTPResponse,
  186. "Response wasn't an HTTP response, internal error \(urlResponse)"
  187. )
  188. throw URLError(
  189. .badServerResponse,
  190. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  191. )
  192. }
  193. return response
  194. }
  195. private func jsonData(jsonText: String) throws -> Data {
  196. guard let data = jsonText.data(using: .utf8) else {
  197. throw DecodingError.dataCorrupted(DecodingError.Context(
  198. codingPath: [],
  199. debugDescription: "Could not parse response as UTF8."
  200. ))
  201. }
  202. return data
  203. }
  204. private func parseError(responseBody: String) -> Error {
  205. do {
  206. let data = try jsonData(jsonText: responseBody)
  207. return parseError(responseData: data)
  208. } catch {
  209. return error
  210. }
  211. }
  212. private func parseError(responseData: Data) -> Error {
  213. do {
  214. let rpcError = try JSONDecoder().decode(BackendError.self, from: responseData)
  215. logRPCError(rpcError)
  216. return rpcError
  217. } catch {
  218. // TODO: Return an error about an unrecognized error payload with the response body
  219. return error
  220. }
  221. }
  222. // Log specific RPC errors that cannot be mitigated or handled by user code.
  223. // These errors do not produce specific GenerateContentError or CountTokensError cases.
  224. private func logRPCError(_ error: BackendError) {
  225. let projectID = firebaseInfo.projectID
  226. if error.isVertexAIInFirebaseServiceDisabledError() {
  227. AILog.error(code: .vertexAIInFirebaseAPIDisabled, """
  228. The Firebase AI SDK requires the Firebase AI API \
  229. (`firebasevertexai.googleapis.com`) to be enabled in your Firebase project. Enable this API \
  230. by visiting the Firebase Console at
  231. https://console.firebase.google.com/project/\(projectID)/genai/ and clicking "Get started". \
  232. If you enabled this API recently, wait a few minutes for the action to propagate to our \
  233. systems and then retry.
  234. """)
  235. }
  236. }
  237. private func parseResponse<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
  238. do {
  239. return try JSONDecoder().decode(type, from: data)
  240. } catch {
  241. if let json = String(data: data, encoding: .utf8) {
  242. AILog.error(code: .loadRequestParseResponseFailedJSON, "JSON response: \(json)")
  243. }
  244. AILog.error(
  245. code: .loadRequestParseResponseFailedJSONError,
  246. "Error decoding server JSON: \(error)"
  247. )
  248. throw error
  249. }
  250. }
  251. #if DEBUG
  252. private func cURLCommand(from request: URLRequest) -> String {
  253. var returnValue = "curl "
  254. if let allHeaders = request.allHTTPHeaderFields {
  255. for (key, value) in allHeaders {
  256. returnValue += "-H '\(key): \(value)' "
  257. }
  258. }
  259. guard let url = request.url else { return "" }
  260. returnValue += "'\(url.absoluteString)' "
  261. guard let body = request.httpBody,
  262. let jsonStr = String(bytes: body, encoding: .utf8) else { return "" }
  263. let escapedJSON = jsonStr.replacingOccurrences(of: "'", with: "'\\''")
  264. returnValue += "-d '\(escapedJSON)'"
  265. return returnValue
  266. }
  267. private func printCURLCommand(from request: URLRequest) {
  268. guard AILog.additionalLoggingEnabled() else {
  269. return
  270. }
  271. let command = cURLCommand(from: request)
  272. os_log(.debug, log: AILog.logObject, """
  273. \(AILog.service) Creating request with the equivalent cURL command:
  274. ----- cURL command -----
  275. \(command, privacy: .private)
  276. ------------------------
  277. """)
  278. }
  279. #endif // DEBUG
  280. }