Skip to content

Commit 9b16e48

Browse files
authored
[Vertex AI] Fix CountTokensResponse decoding (#14447)
1 parent 44fe5d0 commit 9b16e48

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

FirebaseVertexAI/Sources/CountTokensRequest.swift

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,19 @@ extension CountTokensRequest: Encodable {
6464
}
6565

6666
@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
67-
extension CountTokensResponse: Decodable {}
67+
extension CountTokensResponse: Decodable {
68+
enum CodingKeys: CodingKey {
69+
case totalTokens
70+
case totalBillableCharacters
71+
case promptTokensDetails
72+
}
73+
74+
public init(from decoder: any Decoder) throws {
75+
let container = try decoder.container(keyedBy: CodingKeys.self)
76+
totalTokens = try container.decodeIfPresent(Int.self, forKey: .totalTokens) ?? 0
77+
totalBillableCharacters =
78+
try container.decodeIfPresent(Int.self, forKey: .totalBillableCharacters)
79+
promptTokensDetails =
80+
try container.decodeIfPresent([ModalityTokenCount].self, forKey: .promptTokensDetails) ?? []
81+
}
82+
}

FirebaseVertexAI/Sources/GenerateContentResponse.swift

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -312,15 +312,15 @@ extension GenerateContentResponse.UsageMetadata: Decodable {
312312
public init(from decoder: any Decoder) throws {
313313
let container = try decoder.container(keyedBy: CodingKeys.self)
314314
promptTokenCount = try container.decodeIfPresent(Int.self, forKey: .promptTokenCount) ?? 0
315-
candidatesTokenCount = try container
316-
.decodeIfPresent(Int.self, forKey: .candidatesTokenCount) ?? 0
315+
candidatesTokenCount =
316+
try container.decodeIfPresent(Int.self, forKey: .candidatesTokenCount) ?? 0
317317
totalTokenCount = try container.decodeIfPresent(Int.self, forKey: .totalTokenCount) ?? 0
318-
promptTokensDetails = try container
319-
.decodeIfPresent([ModalityTokenCount].self, forKey: .promptTokensDetails) ??
320-
[ModalityTokenCount]()
321-
candidatesTokensDetails = try container
322-
.decodeIfPresent([ModalityTokenCount].self, forKey: .candidatesTokensDetails) ??
323-
[ModalityTokenCount]()
318+
promptTokensDetails =
319+
try container.decodeIfPresent([ModalityTokenCount].self, forKey: .promptTokensDetails) ?? []
320+
candidatesTokensDetails = try container.decodeIfPresent(
321+
[ModalityTokenCount].self,
322+
forKey: .candidatesTokensDetails
323+
) ?? []
324324
}
325325
}
326326

0 commit comments

Comments
 (0)