CountTokensRequest.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2023 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. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  16. struct CountTokensRequest {
  17. let model: String
  18. let contents: [ModelContent]
  19. let options: RequestOptions
  20. }
  21. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  22. extension CountTokensRequest: Encodable {
  23. enum CodingKeys: CodingKey {
  24. case contents
  25. }
  26. }
  27. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  28. extension CountTokensRequest: GenerativeAIRequest {
  29. typealias Response = CountTokensResponse
  30. var url: URL {
  31. URL(string: "\(GenerativeAISwift.baseURL)/\(options.apiVersion)/\(model):countTokens")!
  32. }
  33. }
  34. /// The model's response to a count tokens request.
  35. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  36. public struct CountTokensResponse {
  37. /// The total number of tokens in the input given to the model as a prompt.
  38. public let totalTokens: Int
  39. /// The total number of billable characters in the text input given to the model as a prompt.
  40. ///
  41. /// > Important: This does not include billable image, video or other non-text input. See
  42. /// [Vertex AI pricing](https://cloud.google.com/vertex-ai/generative-ai/pricing) for details.
  43. public let totalBillableCharacters: Int
  44. }
  45. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  46. extension CountTokensResponse: Decodable {
  47. enum CodingKeys: CodingKey {
  48. case totalTokens
  49. case totalBillableCharacters
  50. }
  51. public init(from decoder: any Decoder) throws {
  52. let container = try decoder.container(keyedBy: CodingKeys.self)
  53. totalTokens = try container.decode(Int.self, forKey: .totalTokens)
  54. totalBillableCharacters = try container.decodeIfPresent(
  55. Int.self,
  56. forKey: .totalBillableCharacters
  57. ) ?? 0
  58. }
  59. }