AILog.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // Copyright 2024 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. import os.log
  16. internal import FirebaseCoreExtension
  17. enum AILog {
  18. /// Log message codes for the Firebase AI SDK
  19. ///
  20. /// These codes should ideally not be re-used in order to facilitate matching error codes in
  21. /// support requests to lines in the SDK. These codes should range between 0 and 999999 to avoid
  22. /// being truncated in log messages.
  23. enum MessageCode: Int {
  24. // Logging Configuration
  25. case verboseLoggingDisabled = 100
  26. case verboseLoggingEnabled = 101
  27. // API Enablement Errors
  28. case vertexAIInFirebaseAPIDisabled = 200
  29. // Generative Model Configuration
  30. case generativeModelInitialized = 1000
  31. case unsupportedGeminiModel = 1001
  32. case invalidSchemaFormat = 1002
  33. // Imagen Model Configuration
  34. case unsupportedImagenModel = 1200
  35. case imagenInvalidJPEGCompressionQuality = 1201
  36. // Network Errors
  37. case generativeAIServiceNonHTTPResponse = 2000
  38. case loadRequestResponseError = 2001
  39. case loadRequestResponseErrorPayload = 2002
  40. case loadRequestStreamResponseError = 2003
  41. case loadRequestStreamResponseErrorPayload = 2004
  42. // Parsing Errors
  43. case loadRequestParseResponseFailedJSON = 3000
  44. case loadRequestParseResponseFailedJSONError = 3001
  45. case generateContentResponseUnrecognizedFinishReason = 3002
  46. case generateContentResponseUnrecognizedBlockReason = 3003
  47. case generateContentResponseUnrecognizedBlockThreshold = 3004
  48. case generateContentResponseUnrecognizedHarmProbability = 3005
  49. case generateContentResponseUnrecognizedHarmCategory = 3006
  50. case generateContentResponseUnrecognizedHarmSeverity = 3007
  51. case decodedInvalidProtoDateYear = 3008
  52. case decodedInvalidProtoDateMonth = 3009
  53. case decodedInvalidProtoDateDay = 3010
  54. case decodedInvalidCitationPublicationDate = 3011
  55. case generateContentResponseUnrecognizedContentModality = 3012
  56. case decodedUnsupportedImagenPredictionType = 3013
  57. case decodedUnsupportedPartData = 3014
  58. case codeExecutionResultUnrecognizedOutcome = 3015
  59. case executableCodeUnrecognizedLanguage = 3016
  60. case fallbackValueUsed = 3017
  61. // SDK State Errors
  62. case generateContentResponseNoCandidates = 4000
  63. case generateContentResponseNoText = 4001
  64. case appCheckTokenFetchFailed = 4002
  65. case generateContentResponseEmptyCandidates = 4003
  66. // SDK Debugging
  67. case loadRequestStreamResponseLine = 5000
  68. }
  69. /// Subsystem that should be used for all Loggers.
  70. static let subsystem = "com.google.firebase"
  71. /// Log identifier for the AI SDK.
  72. ///
  73. /// > Note: This corresponds to the `category` in `OSLog`.
  74. static let service = "[FirebaseAI]"
  75. /// The raw `OSLog` log object.
  76. ///
  77. /// > Important: This is only needed for direct `os_log` usage.
  78. static let logObject = OSLog(subsystem: subsystem, category: service)
  79. /// The argument required to enable additional logging.
  80. static let enableArgumentKey = "-FIRDebugEnabled"
  81. static func log(level: FirebaseLoggerLevel, code: MessageCode, _ message: String) {
  82. let messageCode = String(format: "I-VTX%06d", code.rawValue)
  83. FirebaseLogger.log(
  84. level: level,
  85. service: AILog.service,
  86. code: messageCode,
  87. message: message
  88. )
  89. }
  90. static func error(code: MessageCode, _ message: String) {
  91. log(level: .error, code: code, message)
  92. }
  93. static func warning(code: MessageCode, _ message: String) {
  94. log(level: .warning, code: code, message)
  95. }
  96. static func notice(code: MessageCode, _ message: String) {
  97. log(level: .notice, code: code, message)
  98. }
  99. static func info(code: MessageCode, _ message: String) {
  100. log(level: .info, code: code, message)
  101. }
  102. static func debug(code: MessageCode, _ message: String) {
  103. log(level: .debug, code: code, message)
  104. }
  105. /// Returns `true` if additional logging has been enabled via a launch argument.
  106. static func additionalLoggingEnabled() -> Bool {
  107. return ProcessInfo.processInfo.arguments.contains(enableArgumentKey)
  108. }
  109. /// Returns the unwrapped optional value if non-nil or returns the fallback value and logs.
  110. ///
  111. /// This convenience method is intended for use in place of `optionalValue ?? fallbackValue` with
  112. /// the addition of logging on use of the fallback value.
  113. ///
  114. /// - Parameters:
  115. /// - optionalValue: The value to unwrap.
  116. /// - fallbackValue: The fallback (default) value to return when `optionalValue` is `nil`.
  117. /// - level: The logging level to use for fallback messages; defaults to
  118. /// `FirebaseLoggerLevel.warning`.
  119. /// - code: The message code to use for fallback messages; defaults to
  120. /// `MessageCode.fallbackValueUsed`.
  121. /// - caller: The name of the unwrapped value; defaults to the name of the computed property or
  122. /// function name from which the unwrapping occurred.
  123. static func safeUnwrap<T>(_ optionalValue: T?,
  124. fallback fallbackValue: T,
  125. level: FirebaseLoggerLevel = .warning,
  126. code: MessageCode = .fallbackValueUsed,
  127. caller: String = #function) -> T {
  128. guard let unwrappedValue = optionalValue else {
  129. AILog.log(level: level, code: code, """
  130. No value specified for '\(caller)' (\(T.self)); using fallback value '\(fallbackValue)'.
  131. """)
  132. return fallbackValue
  133. }
  134. return unwrappedValue
  135. }
  136. }