GenerateContentRequest.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 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  16. struct GenerateContentRequest: Sendable {
  17. /// Model name.
  18. let model: String
  19. let contents: [ModelContent]
  20. let generationConfig: GenerationConfig?
  21. let safetySettings: [SafetySetting]?
  22. let tools: [Tool]?
  23. let toolConfig: ToolConfig?
  24. let systemInstruction: ModelContent?
  25. let apiConfig: APIConfig
  26. let apiMethod: APIMethod
  27. let options: RequestOptions
  28. }
  29. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  30. extension GenerateContentRequest: Encodable {
  31. enum CodingKeys: String, CodingKey {
  32. case contents
  33. case generationConfig
  34. case safetySettings
  35. case tools
  36. case toolConfig
  37. case systemInstruction
  38. }
  39. }
  40. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  41. extension GenerateContentRequest {
  42. enum APIMethod: String {
  43. case generateContent
  44. case streamGenerateContent
  45. case countTokens
  46. }
  47. }
  48. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  49. extension GenerateContentRequest: GenerativeAIRequest {
  50. typealias Response = GenerateContentResponse
  51. var url: URL {
  52. let modelURL = "\(apiConfig.service.endpoint.rawValue)/\(apiConfig.version.rawValue)/\(model)"
  53. switch apiMethod {
  54. case .generateContent:
  55. return URL(string: "\(modelURL):\(apiMethod.rawValue)")!
  56. case .streamGenerateContent:
  57. return URL(string: "\(modelURL):\(apiMethod.rawValue)?alt=sse")!
  58. case .countTokens:
  59. fatalError("\(Self.self) should be a property of \(CountTokensRequest.self).")
  60. }
  61. }
  62. }