Skip to content

Commit

Permalink
Add helper methods for each logging level
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewheard committed Sep 24, 2024
1 parent 4406c2e commit 4d248c0
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 146 deletions.
28 changes: 12 additions & 16 deletions FirebaseVertexAI/Sources/GenerateContentResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ public struct GenerateContentResponse: Sendable {
/// The response's content as text, if it exists.
public var text: String? {
guard let candidate = candidates.first else {
Logging.logEvent(
level: .error,
message: "Could not get text from a response that had no candidates.",
messageCode: .generateContentResponseNoCandidates
VertexLog.error(
code: .generateContentResponseNoCandidates,
"Could not get text from a response that had no candidates."
)
return nil
}
Expand All @@ -56,10 +55,9 @@ public struct GenerateContentResponse: Sendable {
return text
}
guard textValues.count > 0 else {
Logging.logEvent(
level: .error,
message: "Could not get a text part from the first candidate.",
messageCode: .generateContentResponseNoText
VertexLog.error(
code: .generateContentResponseNoText,
"Could not get a text part from the first candidate."
)
return nil
}
Expand Down Expand Up @@ -336,10 +334,9 @@ extension FinishReason: Decodable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
guard let decodedFinishReason = FinishReason(rawValue: value) else {
Logging.logEvent(
level: .error,
message: "Unrecognized FinishReason with value \"\(value)\".",
messageCode: .generateContentResponseUnrecognizedFinishReason
VertexLog.error(
code: .generateContentResponseUnrecognizedFinishReason,
"Unrecognized FinishReason with value \"\(value)\"."
)
self = .unknown
return
Expand All @@ -354,10 +351,9 @@ extension PromptFeedback.BlockReason: Decodable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
guard let decodedBlockReason = PromptFeedback.BlockReason(rawValue: value) else {
Logging.logEvent(
level: .error,
message: "Unrecognized BlockReason with value \"\(value)\".",
messageCode: .generateContentResponseUnrecognizedBlockReason
VertexLog.error(
code: .generateContentResponseUnrecognizedBlockReason,
"Unrecognized BlockReason with value \"\(value)\"."
)
self = .unknown
return
Expand Down
71 changes: 28 additions & 43 deletions FirebaseVertexAI/Sources/GenerativeAIService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,14 @@ struct GenerativeAIService {

// Verify the status code is 200
guard response.statusCode == 200 else {
Logging.logEvent(
level: .error,
message: "The server responded with an error: \(response)",
messageCode: .loadRequestResponseError
VertexLog.error(
code: .loadRequestResponseError,
"The server responded with an error: \(response)"
)
if let responseString = String(data: data, encoding: .utf8) {
Logging.logEvent(
level: .error,
message: "Response payload: \(responseString)",
messageCode: .loadRequestResponseErrorPayload
VertexLog.error(
code: .loadRequestResponseErrorPayload,
"Response payload: \(responseString)"
)
}

Expand Down Expand Up @@ -117,20 +115,18 @@ struct GenerativeAIService {

// Verify the status code is 200
guard response.statusCode == 200 else {
Logging.logEvent(
level: .error,
message: "The server responded with an error: \(response)",
messageCode: .loadRequestStreamResponseError
VertexLog.error(
code: .loadRequestStreamResponseError,
"The server responded with an error: \(response)"
)
var responseBody = ""
for try await line in stream.lines {
responseBody += line + "\n"
}

Logging.logEvent(
level: .error,
message: "Response payload: \(responseBody)",
messageCode: .loadRequestStreamResponseErrorPayload
VertexLog.error(
code: .loadRequestStreamResponseErrorPayload,
"Response payload: \(responseBody)"
)
continuation.finish(throwing: parseError(responseBody: responseBody))

Expand All @@ -143,11 +139,7 @@ struct GenerativeAIService {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
for try await line in stream.lines {
Logging.logEvent(
level: .debug,
message: "Stream response: \(line)",
messageCode: .loadRequestStreamResponseLine
)
VertexLog.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 @@ -199,10 +191,9 @@ struct GenerativeAIService {
let tokenResult = await appCheck.getToken(forcingRefresh: false)
urlRequest.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
if let error = tokenResult.error {
Logging.logEvent(
level: .error,
message: "Failed to fetch AppCheck token. Error: \(error)",
messageCode: .appCheckTokenFetchFailed
VertexLog.error(
code: .appCheckTokenFetchFailed,
"Failed to fetch AppCheck token. Error: \(error)"
)
}
}
Expand All @@ -225,10 +216,9 @@ struct GenerativeAIService {
private func httpResponse(urlResponse: URLResponse) throws -> HTTPURLResponse {
// Verify the status code is 200
guard let response = urlResponse as? HTTPURLResponse else {
Logging.logEvent(
level: .error,
message: "Response wasn't an HTTP response, internal error \(urlResponse)",
messageCode: .generativeAIServiceNonHTTPResponse
VertexLog.error(
code: .generativeAIServiceNonHTTPResponse,
"Response wasn't an HTTP response, internal error \(urlResponse)"
)
throw NSError(
domain: "com.google.generative-ai",
Expand Down Expand Up @@ -277,14 +267,14 @@ struct GenerativeAIService {
// These errors do not produce specific GenerateContentError or CountTokensError cases.
private func logRPCError(_ error: RPCError) {
if error.isFirebaseMLServiceDisabledError() {
Logging.logEvent(level: .error, message: """
VertexLog.error(code: .firebaseMLAPIDisabled, """
The Vertex AI for Firebase SDK requires the Firebase ML API `firebaseml.googleapis.com` to \
be enabled for your project. Get started in the Firebase Console \
(https://console.firebase.google.com/project/\(projectID)/genai/vertex) or verify that the \
API is enabled in the Google Cloud Console \
(https://console.developers.google.com/apis/api/firebaseml.googleapis.com/overview?project=\
\(projectID)).
""", messageCode: .firebaseMLAPIDisabled)
""")
}
}

Expand All @@ -293,16 +283,11 @@ struct GenerativeAIService {
return try JSONDecoder().decode(type, from: data)
} catch {
if let json = String(data: data, encoding: .utf8) {
Logging.logEvent(
level: .error,
message: "JSON response: \(json)",
messageCode: .loadRequestParseResponseFailedJSON
)
VertexLog.error(code: .loadRequestParseResponseFailedJSON, "JSON response: \(json)")
}
Logging.logEvent(
level: .error,
message: "Error decoding server JSON: \(error)",
messageCode: .loadRequestParseResponseFailedJSONError
VertexLog.error(
code: .loadRequestParseResponseFailedJSONError,
"Error decoding server JSON: \(error)"
)
throw error
}
Expand All @@ -329,12 +314,12 @@ struct GenerativeAIService {
}

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

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

/// Generates content from String and/or image inputs, given to the model as a prompt, that are
Expand Down
67 changes: 0 additions & 67 deletions FirebaseVertexAI/Sources/Logging.swift

This file was deleted.

13 changes: 7 additions & 6 deletions FirebaseVertexAI/Sources/Safety.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,9 @@ extension SafetyRating.HarmProbability: Decodable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
guard let decodedProbability = SafetyRating.HarmProbability(rawValue: value) else {
Logging.logEvent(
level: .error,
message: "Unrecognized HarmProbability with value \"\(value)\".",
messageCode: .generateContentResponseUnrecognizedHarmProbability
VertexLog.error(
code: .generateContentResponseUnrecognizedHarmProbability,
"Unrecognized HarmProbability with value \"\(value)\"."
)
self = .unknown
return
Expand All @@ -142,8 +141,10 @@ extension HarmCategory: Codable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
guard let decodedCategory = HarmCategory(rawValue: value) else {
Logging.default
.error("[FirebaseVertexAI] Unrecognized HarmCategory with value \"\(value)\".")
VertexLog.error(
code: .generateContentResponseUnrecognizedHarmCategory,
"Unrecognized HarmCategory with value \"\(value)\"."
)
self = .unknown
return
}
Expand Down
Loading

0 comments on commit 4d248c0

Please sign in to comment.