Skip to content

Renames for console logging #14776

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import os.log

internal import FirebaseCoreExtension

enum VertexLog {
/// Log message codes for the Vertex AI SDK
enum AILog {
/// Log message codes for the Firebase AI SDK
///
/// These codes should ideally not be re-used in order to facilitate matching error codes in
/// support requests to lines in the SDK. These codes should range between 0 and 999999 to avoid
Expand Down Expand Up @@ -75,10 +75,10 @@ enum VertexLog {
/// Subsystem that should be used for all Loggers.
static let subsystem = "com.google.firebase"

/// Log identifier for the Vertex AI SDK.
/// Log identifier for the AI SDK.
///
/// > Note: This corresponds to the `category` in `OSLog`.
static let service = "[FirebaseVertexAI]"
static let service = "[FirebaseAI]"

/// The raw `OSLog` log object.
///
Expand All @@ -92,7 +92,7 @@ enum VertexLog {
let messageCode = String(format: "I-VTX%06d", code.rawValue)
FirebaseLogger.log(
level: level,
service: VertexLog.service,
service: AILog.service,
code: messageCode,
message: message
)
Expand Down
4 changes: 2 additions & 2 deletions FirebaseAI/Sources/FirebaseAI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public final class FirebaseAI: Sendable {
requestOptions: RequestOptions = RequestOptions())
-> GenerativeModel {
if !modelName.starts(with: GenerativeModel.geminiModelNamePrefix) {
VertexLog.warning(code: .unsupportedGeminiModel, """
AILog.warning(code: .unsupportedGeminiModel, """
Unsupported Gemini model "\(modelName)"; see \
https://firebase.google.com/docs/vertex-ai/models for a list supported Gemini model names.
""")
Expand Down Expand Up @@ -113,7 +113,7 @@ public final class FirebaseAI: Sendable {
safetySettings: ImagenSafetySettings? = nil,
requestOptions: RequestOptions = RequestOptions()) -> ImagenModel {
if !modelName.starts(with: ImagenModel.imagenModelNamePrefix) {
VertexLog.warning(code: .unsupportedImagenModel, """
AILog.warning(code: .unsupportedImagenModel, """
Unsupported Imagen model "\(modelName)"; see \
https://firebase.google.com/docs/vertex-ai/models for a list supported Imagen model names.
""")
Expand Down
12 changes: 6 additions & 6 deletions FirebaseAI/Sources/GenerateContentResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public struct GenerateContentResponse: Sendable {
/// The response's content as text, if it exists.
public var text: String? {
guard let candidate = candidates.first else {
VertexLog.error(
AILog.error(
code: .generateContentResponseNoCandidates,
"Could not get text from a response that had no candidates."
)
Expand All @@ -64,7 +64,7 @@ public struct GenerateContentResponse: Sendable {
}
}
guard textValues.count > 0 else {
VertexLog.error(
AILog.error(
code: .generateContentResponseNoText,
"Could not get a text part from the first candidate."
)
Expand All @@ -91,7 +91,7 @@ public struct GenerateContentResponse: Sendable {
/// Returns inline data parts found in any `Part`s of the first candidate of the response, if any.
public var inlineDataParts: [InlineDataPart] {
guard let candidate = candidates.first else {
VertexLog.error(code: .generateContentResponseNoCandidates, """
AILog.error(code: .generateContentResponseNoCandidates, """
Could not get inline data parts because the response has no candidates. The accessor only \
checks the first candidate.
""")
Expand Down Expand Up @@ -219,7 +219,7 @@ public struct FinishReason: DecodableProtoEnum, Hashable, Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedFinishReason
AILog.MessageCode.generateContentResponseUnrecognizedFinishReason
}

/// A metadata struct containing any feedback the model had on the prompt it was provided.
Expand Down Expand Up @@ -254,7 +254,7 @@ public struct PromptFeedback: Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedBlockReason
AILog.MessageCode.generateContentResponseUnrecognizedBlockReason
}

/// The reason a prompt was blocked, if it was blocked.
Expand Down Expand Up @@ -428,7 +428,7 @@ extension Citation: Decodable {
) {
publicationDate = publicationProtoDate.dateComponents
if let publicationDate, !publicationDate.isValidDate {
VertexLog.warning(
AILog.warning(
code: .decodedInvalidCitationPublicationDate,
"Decoded an invalid citation publication date: \(publicationDate)"
)
Expand Down
28 changes: 14 additions & 14 deletions FirebaseAI/Sources/GenerativeAIService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ struct GenerativeAIService {

// Verify the status code is 200
guard response.statusCode == 200 else {
VertexLog.error(
AILog.error(
code: .loadRequestResponseError,
"The server responded with an error: \(response)"
)
if let responseString = String(data: data, encoding: .utf8) {
VertexLog.error(
AILog.error(
code: .loadRequestResponseErrorPayload,
"Response payload: \(responseString)"
)
Expand Down Expand Up @@ -104,7 +104,7 @@ struct GenerativeAIService {

// Verify the status code is 200
guard response.statusCode == 200 else {
VertexLog.error(
AILog.error(
code: .loadRequestStreamResponseError,
"The server responded with an error: \(response)"
)
Expand All @@ -113,7 +113,7 @@ struct GenerativeAIService {
responseBody += line + "\n"
}

VertexLog.error(
AILog.error(
code: .loadRequestStreamResponseErrorPayload,
"Response payload: \(responseBody)"
)
Expand All @@ -128,7 +128,7 @@ struct GenerativeAIService {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
for try await line in stream.lines {
VertexLog.debug(code: .loadRequestStreamResponseLine, "Stream response: \(line)")
AILog.debug(code: .loadRequestStreamResponseLine, "Stream response: \(line)")

if line.hasPrefix("data:") {
// We can assume 5 characters since it's utf-8 encoded, removing `data:`.
Expand Down Expand Up @@ -180,7 +180,7 @@ struct GenerativeAIService {
let tokenResult = await appCheck.getToken(forcingRefresh: false)
urlRequest.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
if let error = tokenResult.error {
VertexLog.error(
AILog.error(
code: .appCheckTokenFetchFailed,
"Failed to fetch AppCheck token. Error: \(error)"
)
Expand Down Expand Up @@ -212,7 +212,7 @@ struct GenerativeAIService {
// response objects you get back from the URLSession, NSURLConnection, or NSURLDownload class
// are instances of the HTTPURLResponse class."
guard let response = urlResponse as? HTTPURLResponse else {
VertexLog.error(
AILog.error(
code: .generativeAIServiceNonHTTPResponse,
"Response wasn't an HTTP response, internal error \(urlResponse)"
)
Expand Down Expand Up @@ -260,8 +260,8 @@ struct GenerativeAIService {
private func logRPCError(_ error: BackendError) {
let projectID = firebaseInfo.projectID
if error.isVertexAIInFirebaseServiceDisabledError() {
VertexLog.error(code: .vertexAIInFirebaseAPIDisabled, """
The Vertex AI in Firebase SDK requires the Vertex AI in Firebase API \
AILog.error(code: .vertexAIInFirebaseAPIDisabled, """
The Firebase AI SDK requires the Firebase AI API \
(`firebasevertexai.googleapis.com`) to be enabled in your Firebase project. Enable this API \
by visiting the Firebase Console at
https://console.firebase.google.com/project/\(projectID)/genai/ and clicking "Get started". \
Expand All @@ -276,9 +276,9 @@ struct GenerativeAIService {
return try JSONDecoder().decode(type, from: data)
} catch {
if let json = String(data: data, encoding: .utf8) {
VertexLog.error(code: .loadRequestParseResponseFailedJSON, "JSON response: \(json)")
AILog.error(code: .loadRequestParseResponseFailedJSON, "JSON response: \(json)")
}
VertexLog.error(
AILog.error(
code: .loadRequestParseResponseFailedJSONError,
"Error decoding server JSON: \(error)"
)
Expand Down Expand Up @@ -307,12 +307,12 @@ struct GenerativeAIService {
}

private func printCURLCommand(from request: URLRequest) {
guard VertexLog.additionalLoggingEnabled() else {
guard AILog.additionalLoggingEnabled() else {
return
}
let command = cURLCommand(from: request)
os_log(.debug, log: VertexLog.logObject, """
\(VertexLog.service) Creating request with the equivalent cURL command:
os_log(.debug, log: AILog.logObject, """
\(AILog.service) Creating request with the equivalent cURL command:
----- cURL command -----
\(command, privacy: .private)
------------------------
Expand Down
10 changes: 5 additions & 5 deletions FirebaseAI/Sources/GenerativeModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,15 @@ public final class GenerativeModel: Sendable {
}
self.requestOptions = requestOptions

if VertexLog.additionalLoggingEnabled() {
VertexLog.debug(code: .verboseLoggingEnabled, "Verbose logging enabled.")
if AILog.additionalLoggingEnabled() {
AILog.debug(code: .verboseLoggingEnabled, "Verbose logging enabled.")
} else {
VertexLog.info(code: .verboseLoggingDisabled, """
AILog.info(code: .verboseLoggingDisabled, """
[FirebaseVertexAI] To enable additional logging, add \
`\(VertexLog.enableArgumentKey)` as a launch argument in Xcode.
`\(AILog.enableArgumentKey)` as a launch argument in Xcode.
""")
}
VertexLog.debug(code: .generativeModelInitialized, "Model \(modelResourceName) initialized.")
AILog.debug(code: .generativeModelInitialized, "Model \(modelResourceName) initialized.")
}

/// Generates content from String and/or image inputs, given to the model as a prompt, that are
Expand Down
2 changes: 1 addition & 1 deletion FirebaseAI/Sources/ModalityTokenCount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public struct ContentModality: DecodableProtoEnum, Hashable, Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedContentModality
AILog.MessageCode.generateContentResponseUnrecognizedContentModality
}

// MARK: Codable Conformances
Expand Down
6 changes: 3 additions & 3 deletions FirebaseAI/Sources/Protocols/Internal/CodableProtoEnum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ protocol ProtoEnum: Sendable {
/// Protobuf enums are represented as strings in JSON. A default `Decodable` implementation is
/// provided when conforming to this type.
protocol DecodableProtoEnum: ProtoEnum, Decodable {
/// Returns the ``VertexLog/MessageCode`` associated with unrecognized (unknown) enum values.
static var unrecognizedValueMessageCode: VertexLog.MessageCode { get }
/// Returns the ``AILog/MessageCode`` associated with unrecognized (unknown) enum values.
static var unrecognizedValueMessageCode: AILog.MessageCode { get }

/// Creates a new instance by decoding from the given decoder.
///
Expand Down Expand Up @@ -90,7 +90,7 @@ extension DecodableProtoEnum {
self = Self(rawValue: rawValue)

if Kind(rawValue: rawValue) == nil {
VertexLog.error(
AILog.error(
code: Self.unrecognizedValueMessageCode,
"""
Unrecognized \(Self.self) with value "\(rawValue)":
Expand Down
6 changes: 3 additions & 3 deletions FirebaseAI/Sources/Safety.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public struct SafetyRating: Equatable, Hashable, Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedHarmProbability
AILog.MessageCode.generateContentResponseUnrecognizedHarmProbability
}

/// The magnitude of how harmful a model response might be for the respective ``HarmCategory``.
Expand Down Expand Up @@ -139,7 +139,7 @@ public struct SafetyRating: Equatable, Hashable, Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedHarmSeverity
AILog.MessageCode.generateContentResponseUnrecognizedHarmSeverity
}
}

Expand Down Expand Up @@ -263,7 +263,7 @@ public struct HarmCategory: CodableProtoEnum, Hashable, Sendable {
public let rawValue: String

static let unrecognizedValueMessageCode =
VertexLog.MessageCode.generateContentResponseUnrecognizedHarmCategory
AILog.MessageCode.generateContentResponseUnrecognizedHarmCategory
}

// MARK: - Codable Conformances
Expand Down
6 changes: 3 additions & 3 deletions FirebaseAI/Sources/Types/Internal/ProtoDate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ extension ProtoDate: Decodable {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let year = try container.decodeIfPresent(Int.self, forKey: .year), year != 0 {
if year < 0 || year > 9999 {
VertexLog.warning(
AILog.warning(
code: .decodedInvalidProtoDateYear,
"""
Invalid year: \(year); must be from 1 to 9999, or 0 for a date without a specified year.
Expand All @@ -82,7 +82,7 @@ extension ProtoDate: Decodable {

if let month = try container.decodeIfPresent(Int.self, forKey: .month), month != 0 {
if month < 0 || month > 12 {
VertexLog.warning(
AILog.warning(
code: .decodedInvalidProtoDateMonth,
"""
Invalid month: \(month); must be from 1 to 12, or 0 for a year date without a specified \
Expand All @@ -97,7 +97,7 @@ extension ProtoDate: Decodable {

if let day = try container.decodeIfPresent(Int.self, forKey: .day), day != 0 {
if day < 0 || day > 31 {
VertexLog.warning(
AILog.warning(
code: .decodedInvalidProtoDateDay,
"Invalid day: \(day); must be from 1 to 31, or 0 for a date without a specified day."
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ extension ImagenGenerationResponse: Decodable where T: Decodable {
} else if let filteredReason = try? predictionsContainer.decode(RAIFilteredReason.self) {
filteredReasons.append(filteredReason.raiFilteredReason)
} else if let unsupportedPrediction = try? predictionsContainer.decode(JSONObject.self) {
VertexLog.warning(
AILog.warning(
code: .decodedUnsupportedImagenPredictionType,
"Ignoring unsupported Imagen prediction: \(unsupportedPrediction)"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public struct ImagenImageFormat {
/// compression (highest image quality, largest file size); defaults to `75`.
public static func jpeg(compressionQuality: Int? = nil) -> ImagenImageFormat {
if let compressionQuality, compressionQuality < 0 || compressionQuality > 100 {
VertexLog.warning(code: .imagenInvalidJPEGCompressionQuality, """
AILog.warning(code: .imagenInvalidJPEGCompressionQuality, """
Invalid JPEG compression quality of \(compressionQuality) specified; the supported range is \
[0, 100].
""")
Expand Down
2 changes: 1 addition & 1 deletion FirebaseAI/Sources/Types/Public/Schema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ public final class Schema: Sendable {
/// one of these schemas. The array must not be empty.
public static func anyOf(schemas: [Schema]) -> Schema {
if schemas.isEmpty {
VertexLog.error(code: .invalidSchemaFormat, "The `anyOf` schemas array cannot be empty.")
AILog.error(code: .invalidSchemaFormat, "The `anyOf` schemas array cannot be empty.")
}
// Note: The 'type' for an 'anyOf' schema is implicitly defined by the presence of the
// 'anyOf' keyword and doesn't have a specific explicit type like "OBJECT" or "STRING".
Expand Down
Loading