Skip to content
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

Add invalidAPIKey case to GenerateContentError #91

Merged
merged 1 commit into from
Jan 18, 2024
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
41 changes: 40 additions & 1 deletion Sources/GoogleAI/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,21 @@ struct RPCError: Error {
let httpResponseCode: Int
let message: String
let status: RPCStatus
let details: [ErrorDetails]

init(httpResponseCode: Int, message: String, status: RPCStatus) {
private var errorInfo: ErrorDetails? {
return details.first { $0.isErrorInfo() }
}

init(httpResponseCode: Int, message: String, status: RPCStatus, details: [ErrorDetails]) {
self.httpResponseCode = httpResponseCode
self.message = message
self.status = status
self.details = details
}

func isInvalidAPIKeyError() -> Bool {
return errorInfo?.reason == "API_KEY_INVALID"
}
}

Expand Down Expand Up @@ -52,20 +62,44 @@ extension RPCError: Decodable {
} else {
self.status = .unknown
}

details = status.details
}
}

struct ErrorStatus {
let code: Int?
let message: String?
let status: RPCStatus?
let details: [ErrorDetails]
}

struct ErrorDetails {
static let errorInfoType = "type.googleapis.com/google.rpc.ErrorInfo"

let type: String
let reason: String?
let domain: String?

func isErrorInfo() -> Bool {
return type == ErrorDetails.errorInfoType
}
}

extension ErrorDetails: Decodable, Equatable {
enum CodingKeys: String, CodingKey {
case type = "@type"
case reason
case domain
}
}

extension ErrorStatus: Decodable {
enum CodingKeys: CodingKey {
case code
case message
case status
case details
}

init(from decoder: Decoder) throws {
Expand All @@ -77,6 +111,11 @@ extension ErrorStatus: Decodable {
} catch {
status = .unknown
}
if container.contains(.details) {
details = try container.decode([ErrorDetails].self, forKey: .details)
} else {
details = []
}
}
}

Expand Down
3 changes: 3 additions & 0 deletions Sources/GoogleAI/GenerateContentError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ public enum GenerateContentError: Error {

/// A response didn't fully complete. See the `FinishReason` for more information.
case responseStoppedEarly(reason: FinishReason, response: GenerateContentResponse)

/// The provided API key is invalid.
case invalidAPIKey(underlying: Error)
}
33 changes: 15 additions & 18 deletions Sources/GoogleAI/GenerativeAIService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ struct GenerativeAIService {
Logging.network.error("[GoogleGenerativeAI] Response payload: \(responseString)")
}

throw try JSONDecoder().decode(RPCError.self, from: data)
throw parseError(responseData: data)
}

return try parseResponse(T.Response.self, from: data)
Expand Down Expand Up @@ -96,11 +96,7 @@ struct GenerativeAIService {
}

Logging.network.error("[GoogleGenerativeAI] Response payload: \(responseBody)")
do {
try parseError(responseBody: responseBody)
} catch {
continuation.finish(throwing: error)
}
continuation.finish(throwing: parseError(responseBody: responseBody))

return
}
Expand Down Expand Up @@ -138,12 +134,7 @@ struct GenerativeAIService {
}

if extraLines.count > 0 {
do {
try parseError(responseBody: extraLines)
} catch {
continuation.finish(throwing: error)
}

continuation.finish(throwing: parseError(responseBody: extraLines))
return
}

Expand Down Expand Up @@ -198,15 +189,21 @@ struct GenerativeAIService {
return data
}

private func parseError(responseBody: String) throws {
let data = try jsonData(jsonText: responseBody)
private func parseError(responseBody: String) -> Error {
do {
let data = try jsonData(jsonText: responseBody)
return parseError(responseData: data)
} catch {
return error
}
}

private func parseError(responseData: Data) -> Error {
do {
let rpcError = try JSONDecoder().decode(RPCError.self, from: data)
throw rpcError
return try JSONDecoder().decode(RPCError.self, from: responseData)
} catch {
// TODO: Throw an error about an unrecognized error payload with the response body
throw error
// TODO: Return an error about an unrecognized error payload with the response body
return error
}
}

Expand Down
3 changes: 3 additions & 0 deletions Sources/GoogleAI/GenerativeModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ public final class GenerativeModel {
do {
response = try await generativeAIService.loadRequest(request: generateContentRequest)
} catch {
if let error = error as? RPCError, error.isInvalidAPIKeyError() {
throw GenerateContentError.invalidAPIKey(underlying: error)
}
throw GenerateContentError.internalError(underlying: error)
}

Expand Down
10 changes: 5 additions & 5 deletions Tests/GoogleAITests/GenerativeModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,12 @@ final class GenerativeModelTests: XCTestCase {
do {
_ = try await model.generateContent(testPrompt)
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
} catch let GenerateContentError.internalError(underlying: rpcError as RPCError) {
XCTAssertEqual(rpcError.status, .invalidArgument)
XCTAssertEqual(rpcError.httpResponseCode, expectedStatusCode)
XCTAssertTrue(rpcError.message.hasPrefix("API key not valid"))
} catch let GenerateContentError.invalidAPIKey(underlying: error as RPCError) {
andrewheard marked this conversation as resolved.
Show resolved Hide resolved
XCTAssertEqual(error.status, .invalidArgument)
XCTAssertEqual(error.httpResponseCode, expectedStatusCode)
XCTAssertTrue(error.message.hasPrefix("API key not valid"))
} catch {
XCTFail("Should throw GenerateContentError.internalError; error thrown: \(error)")
XCTFail("Should throw GenerateContentError.invalidAPIKey; error thrown: \(error)")
}
}

Expand Down
Loading