FunctionCalling.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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, Encodable {
  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. /// A `Schema` object allows the definition of input and output data types.
  23. ///
  24. /// These types can be objects, but also primitives and arrays. Represents a select subset of an
  25. /// [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema).
  26. public class Schema: Encodable {
  27. /// The data type.
  28. let type: DataType
  29. /// The format of the data.
  30. let format: String?
  31. /// A brief description of the parameter.
  32. let description: String?
  33. /// Indicates if the value may be null.
  34. let nullable: Bool?
  35. /// Possible values of the element of type ``DataType/string`` with "enum" format.
  36. let enumValues: [String]?
  37. /// Schema of the elements of type ``DataType/array``.
  38. let items: Schema?
  39. /// Properties of type ``DataType/object``.
  40. let properties: [String: Schema]?
  41. /// Required properties of type ``DataType/object``.
  42. let requiredProperties: [String]?
  43. enum CodingKeys: String, CodingKey {
  44. case type
  45. case format
  46. case description
  47. case nullable
  48. case enumValues = "enum"
  49. case items
  50. case properties
  51. case requiredProperties = "required"
  52. }
  53. /// Constructs a new `Schema`.
  54. ///
  55. /// - Parameters:
  56. /// - type: The data type.
  57. /// - format: The format of the data; used only for primitive datatypes.
  58. /// Supported formats:
  59. /// - ``DataType/integer``: int32, int64
  60. /// - ``DataType/number``: float, double
  61. /// - ``DataType/string``: enum
  62. /// - description: A brief description of the parameter; may be formatted as Markdown.
  63. /// - nullable: Indicates if the value may be null.
  64. /// - enumValues: Possible values of the element of type ``DataType/string`` with "enum" format.
  65. /// For example, an enum `Direction` may be defined as `["EAST", NORTH", "SOUTH", "WEST"]`.
  66. /// - items: Schema of the elements of type ``DataType/array``.
  67. /// - properties: Properties of type ``DataType/object``.
  68. /// - requiredProperties: Required properties of type ``DataType/object``.
  69. public init(type: DataType, format: String? = nil, description: String? = nil,
  70. nullable: Bool? = nil,
  71. enumValues: [String]? = nil, items: Schema? = nil,
  72. properties: [String: Schema]? = nil,
  73. requiredProperties: [String]? = nil) {
  74. self.type = type
  75. self.format = format
  76. self.description = description
  77. self.nullable = nullable
  78. self.enumValues = enumValues
  79. self.items = items
  80. self.properties = properties
  81. self.requiredProperties = requiredProperties
  82. }
  83. }
  84. /// A data type.
  85. ///
  86. /// Contains the set of OpenAPI [data types](https://spec.openapis.org/oas/v3.0.3#data-types).
  87. public enum DataType: String, Encodable {
  88. /// A `String` type.
  89. case string = "STRING"
  90. /// A floating-point number type.
  91. case number = "NUMBER"
  92. /// An integer type.
  93. case integer = "INTEGER"
  94. /// A boolean type.
  95. case boolean = "BOOLEAN"
  96. /// An array type.
  97. case array = "ARRAY"
  98. /// An object type.
  99. case object = "OBJECT"
  100. }
  101. /// Structured representation of a function declaration.
  102. ///
  103. /// This `FunctionDeclaration` is a representation of a block of code that can be used as a ``Tool``
  104. /// by the model and executed by the client.
  105. public struct FunctionDeclaration {
  106. /// The name of the function.
  107. let name: String
  108. /// A brief description of the function.
  109. let description: String
  110. /// Describes the parameters to this function; must be of type ``DataType/object``.
  111. let parameters: Schema?
  112. /// Constructs a new `FunctionDeclaration`.
  113. ///
  114. /// - Parameters:
  115. /// - name: The name of the function; must be a-z, A-Z, 0-9, or contain underscores and dashes,
  116. /// with a maximum length of 63.
  117. /// - description: A brief description of the function.
  118. /// - parameters: Describes the parameters to this function; the keys are parameter names and
  119. /// the values are ``Schema`` objects describing them.
  120. /// - requiredParameters: A list of required parameters by name.
  121. public init(name: String, description: String, parameters: [String: Schema]?,
  122. requiredParameters: [String]?) {
  123. self.name = name
  124. self.description = description
  125. self.parameters = Schema(
  126. type: .object,
  127. properties: parameters,
  128. requiredProperties: requiredParameters
  129. )
  130. }
  131. }
  132. /// Helper tools that the model may use to generate response.
  133. ///
  134. /// A `Tool` is a piece of code that enables the system to interact with external systems to
  135. /// perform an action, or set of actions, outside of knowledge and scope of the model.
  136. public struct Tool: Encodable {
  137. /// A list of `FunctionDeclarations` available to the model.
  138. let functionDeclarations: [FunctionDeclaration]?
  139. /// Constructs a new `Tool`.
  140. ///
  141. /// - Parameters:
  142. /// - functionDeclarations: A list of `FunctionDeclarations` available to the model that can be
  143. /// used for function calling.
  144. /// The model or system does not execute the function. Instead the defined function may be
  145. /// returned as a ``FunctionCall`` in ``ModelContent/Part/functionCall(_:)`` with arguments to
  146. /// the client side for execution. The model may decide to call a subset of these functions by
  147. /// populating ``FunctionCall`` in the response. The next conversation turn may contain a
  148. /// ``FunctionResponse`` in ``ModelContent/Part/functionResponse(_:)`` with the
  149. /// ``ModelContent/role`` "function", providing generation context for the next model turn.
  150. public init(functionDeclarations: [FunctionDeclaration]?) {
  151. self.functionDeclarations = functionDeclarations
  152. }
  153. }
  154. /// Configuration for specifying function calling behavior.
  155. public struct FunctionCallingConfig: Encodable {
  156. /// Defines the execution behavior for function calling by defining the
  157. /// execution mode.
  158. public enum Mode: String, Encodable {
  159. /// The default behavior for function calling. The model calls functions to answer queries at
  160. /// its discretion.
  161. case auto = "AUTO"
  162. /// The model always predicts a provided function call to answer every query.
  163. case any = "ANY"
  164. /// The model will never predict a function call to answer a query. This can also be achieved by
  165. /// not passing any tools to the model.
  166. case none = "NONE"
  167. }
  168. /// Specifies the mode in which function calling should execute. If
  169. /// unspecified, the default value will be set to AUTO.
  170. let mode: Mode?
  171. /// A set of function names that, when provided, limits the functions the model
  172. /// will call.
  173. ///
  174. /// This should only be set when the Mode is ANY. Function names
  175. /// should match [FunctionDeclaration.name]. With mode set to ANY, model will
  176. /// predict a function call from the set of function names provided.
  177. let allowedFunctionNames: [String]?
  178. public init(mode: FunctionCallingConfig.Mode? = nil, allowedFunctionNames: [String]? = nil) {
  179. self.mode = mode
  180. self.allowedFunctionNames = allowedFunctionNames
  181. }
  182. }
  183. /// Tool configuration for any `Tool` specified in the request.
  184. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  185. public struct ToolConfig: Encodable {
  186. let functionCallingConfig: FunctionCallingConfig?
  187. public init(functionCallingConfig: FunctionCallingConfig? = nil) {
  188. self.functionCallingConfig = functionCallingConfig
  189. }
  190. }
  191. /// Result output from a ``FunctionCall``.
  192. ///
  193. /// Contains a string representing the `FunctionDeclaration.name` and a structured JSON object
  194. /// containing any output from the function is used as context to the model. This should contain the
  195. /// result of a ``FunctionCall`` made based on model prediction.
  196. public struct FunctionResponse: Equatable, Encodable {
  197. /// The name of the function that was called.
  198. let name: String
  199. /// The function's response.
  200. let response: JSONObject
  201. /// Constructs a new `FunctionResponse`.
  202. ///
  203. /// - Parameters:
  204. /// - name: The name of the function that was called.
  205. /// - response: The function's response.
  206. public init(name: String, response: JSONObject) {
  207. self.name = name
  208. self.response = response
  209. }
  210. }
  211. // MARK: - Codable Conformance
  212. extension FunctionCall: Decodable {
  213. enum CodingKeys: CodingKey {
  214. case name
  215. case args
  216. }
  217. public init(from decoder: Decoder) throws {
  218. let container = try decoder.container(keyedBy: CodingKeys.self)
  219. name = try container.decode(String.self, forKey: .name)
  220. if let args = try container.decodeIfPresent(JSONObject.self, forKey: .args) {
  221. self.args = args
  222. } else {
  223. args = JSONObject()
  224. }
  225. }
  226. }
  227. extension FunctionDeclaration: Encodable {
  228. enum CodingKeys: String, CodingKey {
  229. case name
  230. case description
  231. case parameters
  232. }
  233. public func encode(to encoder: Encoder) throws {
  234. var container = encoder.container(keyedBy: CodingKeys.self)
  235. try container.encode(name, forKey: .name)
  236. try container.encode(description, forKey: .description)
  237. try container.encode(parameters, forKey: .parameters)
  238. }
  239. }