FunctionCalling.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // Copyright 2024 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. /// A predicted function call returned from the model.
  16. public struct FunctionCall: Equatable, Sendable {
  17. /// The name of the function to call.
  18. public let name: String
  19. /// The function parameters and values.
  20. public let args: JSONObject
  21. }
  22. /// Structured representation of a function declaration.
  23. ///
  24. /// This `FunctionDeclaration` is a representation of a block of code that can be used as a ``Tool``
  25. /// by the model and executed by the client.
  26. public struct FunctionDeclaration {
  27. /// The name of the function.
  28. let name: String
  29. /// A brief description of the function.
  30. let description: String
  31. /// Describes the parameters to this function; must be of type ``DataType/object``.
  32. let parameters: Schema?
  33. /// Constructs a new `FunctionDeclaration`.
  34. ///
  35. /// - Parameters:
  36. /// - name: The name of the function; must be a-z, A-Z, 0-9, or contain underscores and dashes,
  37. /// with a maximum length of 63.
  38. /// - description: A brief description of the function.
  39. /// - parameters: Describes the parameters to this function.
  40. public init(name: String, description: String, parameters: [String: Schema],
  41. optionalParameters: [String] = []) {
  42. self.name = name
  43. self.description = description
  44. self.parameters = Schema.object(
  45. properties: parameters,
  46. optionalProperties: optionalParameters,
  47. nullable: false
  48. )
  49. }
  50. }
  51. /// Helper tools that the model may use to generate response.
  52. ///
  53. /// A `Tool` is a piece of code that enables the system to interact with external systems to
  54. /// perform an action, or set of actions, outside of knowledge and scope of the model.
  55. public struct Tool {
  56. /// A list of `FunctionDeclarations` available to the model.
  57. let functionDeclarations: [FunctionDeclaration]?
  58. /// Constructs a new `Tool`.
  59. ///
  60. /// - Parameters:
  61. /// - functionDeclarations: A list of `FunctionDeclarations` available to the model that can be
  62. /// used for function calling.
  63. /// The model or system does not execute the function. Instead the defined function may be
  64. /// returned as a ``FunctionCall`` in ``ModelContent/Part/functionCall(_:)`` with arguments to
  65. /// the client side for execution. The model may decide to call a subset of these functions by
  66. /// populating ``FunctionCall`` in the response. The next conversation turn may contain a
  67. /// ``FunctionResponse`` in ``ModelContent/Part/functionResponse(_:)`` with the
  68. /// ``ModelContent/role`` "function", providing generation context for the next model turn.
  69. public init(functionDeclarations: [FunctionDeclaration]?) {
  70. self.functionDeclarations = functionDeclarations
  71. }
  72. }
  73. /// Configuration for specifying function calling behavior.
  74. public struct FunctionCallingConfig {
  75. /// Defines the execution behavior for function calling by defining the
  76. /// execution mode.
  77. public enum Mode: String {
  78. /// The default behavior for function calling. The model calls functions to answer queries at
  79. /// its discretion.
  80. case auto = "AUTO"
  81. /// The model always predicts a provided function call to answer every query.
  82. case any = "ANY"
  83. /// The model will never predict a function call to answer a query. This can also be achieved by
  84. /// not passing any tools to the model.
  85. case none = "NONE"
  86. }
  87. /// Specifies the mode in which function calling should execute. If
  88. /// unspecified, the default value will be set to AUTO.
  89. let mode: Mode?
  90. /// A set of function names that, when provided, limits the functions the model
  91. /// will call.
  92. ///
  93. /// This should only be set when the Mode is ANY. Function names
  94. /// should match [FunctionDeclaration.name]. With mode set to ANY, model will
  95. /// predict a function call from the set of function names provided.
  96. let allowedFunctionNames: [String]?
  97. public init(mode: FunctionCallingConfig.Mode? = nil, allowedFunctionNames: [String]? = nil) {
  98. self.mode = mode
  99. self.allowedFunctionNames = allowedFunctionNames
  100. }
  101. }
  102. /// Tool configuration for any `Tool` specified in the request.
  103. public struct ToolConfig {
  104. let functionCallingConfig: FunctionCallingConfig?
  105. public init(functionCallingConfig: FunctionCallingConfig? = nil) {
  106. self.functionCallingConfig = functionCallingConfig
  107. }
  108. }
  109. /// Result output from a ``FunctionCall``.
  110. ///
  111. /// Contains a string representing the `FunctionDeclaration.name` and a structured JSON object
  112. /// containing any output from the function is used as context to the model. This should contain the
  113. /// result of a ``FunctionCall`` made based on model prediction.
  114. public struct FunctionResponse: Equatable, Sendable {
  115. /// The name of the function that was called.
  116. let name: String
  117. /// The function's response.
  118. let response: JSONObject
  119. /// Constructs a new `FunctionResponse`.
  120. ///
  121. /// - Parameters:
  122. /// - name: The name of the function that was called.
  123. /// - response: The function's response.
  124. public init(name: String, response: JSONObject) {
  125. self.name = name
  126. self.response = response
  127. }
  128. }
  129. // MARK: - Codable Conformance
  130. extension FunctionCall: Decodable {
  131. enum CodingKeys: CodingKey {
  132. case name
  133. case args
  134. }
  135. public init(from decoder: Decoder) throws {
  136. let container = try decoder.container(keyedBy: CodingKeys.self)
  137. name = try container.decode(String.self, forKey: .name)
  138. if let args = try container.decodeIfPresent(JSONObject.self, forKey: .args) {
  139. self.args = args
  140. } else {
  141. args = JSONObject()
  142. }
  143. }
  144. }
  145. extension FunctionCall: Encodable {}
  146. extension FunctionDeclaration: Encodable {
  147. enum CodingKeys: String, CodingKey {
  148. case name
  149. case description
  150. case parameters
  151. }
  152. public func encode(to encoder: Encoder) throws {
  153. var container = encoder.container(keyedBy: CodingKeys.self)
  154. try container.encode(name, forKey: .name)
  155. try container.encode(description, forKey: .description)
  156. try container.encode(parameters, forKey: .parameters)
  157. }
  158. }
  159. extension Tool: Encodable {}
  160. extension FunctionCallingConfig: Encodable {}
  161. extension FunctionCallingConfig.Mode: Encodable {}
  162. extension ToolConfig: Encodable {}
  163. extension FunctionResponse: Codable {}