TemplateImagenGenerationRequest.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2025 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. enum ImageAPIMethod: String {
  16. case generateImages = "templatePredict"
  17. }
  18. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  19. struct TemplateImagenGenerationRequest<ImageType: ImagenImageRepresentable>: Sendable {
  20. typealias Response = ImagenGenerationResponse<ImageType>
  21. let template: String
  22. let inputs: [String: TemplateInput]
  23. let projectID: String
  24. let apiConfig: APIConfig
  25. let options: RequestOptions
  26. init(template: String, inputs: [String: TemplateInput], projectID: String,
  27. apiConfig: APIConfig, options: RequestOptions) {
  28. self.template = template
  29. self.inputs = inputs
  30. self.projectID = projectID
  31. self.apiConfig = apiConfig
  32. self.options = options
  33. }
  34. }
  35. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  36. extension TemplateImagenGenerationRequest: GenerativeAIRequest where ImageType: Decodable {
  37. func getURL() throws -> URL {
  38. var urlString =
  39. "\(apiConfig.service.endpoint.rawValue)/\(apiConfig.version.rawValue)/projects/\(projectID)"
  40. if case let .vertexAI(_, location) = apiConfig.service {
  41. urlString += "/locations/\(location)"
  42. }
  43. urlString += "/templates/\(template):\(ImageAPIMethod.generateImages.rawValue)"
  44. guard let url = URL(string: urlString) else {
  45. throw AILog.makeInternalError(message: "Malformed URL: \(urlString)", code: .malformedURL)
  46. }
  47. return url
  48. }
  49. }
  50. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  51. extension TemplateImagenGenerationRequest: Encodable {
  52. enum CodingKeys: String, CodingKey {
  53. case inputs
  54. }
  55. func encode(to encoder: Encoder) throws {
  56. var container = encoder.container(keyedBy: CodingKeys.self)
  57. try container.encode(inputs, forKey: .inputs)
  58. }
  59. }