-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathGenerativeModel.swift
376 lines (344 loc) · 17.4 KB
/
GenerativeModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// A type that represents a remote multimodal model (like Gemini), with the ability to generate
/// content based on various input types.
@available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
public final class GenerativeModel {
// The prefix for a model resource in the Gemini API.
private static let modelResourcePrefix = "models/"
/// The resource name of the model in the backend; has the format "models/model-name".
let modelResourceName: String
/// The backing service responsible for sending and receiving model requests to the backend.
let generativeAIService: GenerativeAIService
/// Configuration parameters used for the MultiModalModel.
let generationConfig: GenerationConfig?
/// The safety settings to be used for prompts.
let safetySettings: [SafetySetting]?
/// A list of tools the model may use to generate the next response.
let tools: [Tool]?
/// Tool configuration for any `Tool` specified in the request.
let toolConfig: ToolConfig?
/// Instructions that direct the model to behave a certain way.
let systemInstruction: ModelContent?
/// Configuration parameters for sending requests to the backend.
let requestOptions: RequestOptions
/// Initializes a new remote model with the given parameters.
///
/// - Parameters:
/// - name: The name of the model to use, for example `"gemini-1.5-pro-latest"`; see
/// [Gemini models](https://ai.google.dev/models/gemini) for a list of supported model names.
/// - apiKey: The API key for your project.
/// - generationConfig: The content generation parameters your model should use.
/// - safetySettings: A value describing what types of harmful content your model should allow.
/// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
/// - systemInstruction: Instructions that direct the model to behave a certain way; currently
/// only text content is supported, for example
/// `ModelContent(role: "system", parts: "You are a cat. Your name is Neko.")`.
/// - toolConfig: Tool configuration for any `Tool` specified in the request.
/// - requestOptions Configuration parameters for sending requests to the backend.
public convenience init(name: String,
apiKey: String,
generationConfig: GenerationConfig? = nil,
safetySettings: [SafetySetting]? = nil,
tools: [Tool]? = nil,
toolConfig: ToolConfig? = nil,
systemInstruction: ModelContent? = nil,
requestOptions: RequestOptions = RequestOptions()) {
self.init(
name: name,
apiKey: apiKey,
generationConfig: generationConfig,
safetySettings: safetySettings,
tools: tools,
toolConfig: toolConfig,
systemInstruction: systemInstruction,
requestOptions: requestOptions,
urlSession: .shared
)
}
/// Initializes a new remote model with the given parameters.
///
/// - Parameters:
/// - name: The name of the model to use, e.g., `"gemini-1.5-pro-latest"`; see
/// [Gemini models](https://ai.google.dev/models/gemini) for a list of supported model names.
/// - apiKey: The API key for your project.
/// - generationConfig: The content generation parameters your model should use.
/// - safetySettings: A value describing what types of harmful content your model should allow.
/// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
/// - systemInstruction: Instructions that direct the model to behave a certain way; currently
/// only text content is supported, e.g., "You are a cat. Your name is Neko."
/// - toolConfig: Tool configuration for any `Tool` specified in the request.
/// - requestOptions Configuration parameters for sending requests to the backend.
public convenience init(name: String,
apiKey: String,
generationConfig: GenerationConfig? = nil,
safetySettings: [SafetySetting]? = nil,
tools: [Tool]? = nil,
toolConfig: ToolConfig? = nil,
systemInstruction: String...,
requestOptions: RequestOptions = RequestOptions()) {
self.init(
name: name,
apiKey: apiKey,
generationConfig: generationConfig,
safetySettings: safetySettings,
tools: tools,
toolConfig: toolConfig,
systemInstruction: ModelContent(
role: "system",
parts: systemInstruction.map { ModelContent.Part.text($0) }
),
requestOptions: requestOptions,
urlSession: .shared
)
}
/// The designated initializer for this class.
init(name: String,
apiKey: String,
generationConfig: GenerationConfig? = nil,
safetySettings: [SafetySetting]? = nil,
tools: [Tool]? = nil,
toolConfig: ToolConfig? = nil,
systemInstruction: ModelContent? = nil,
requestOptions: RequestOptions = RequestOptions(),
urlSession: URLSession) {
modelResourceName = GenerativeModel.modelResourceName(name: name)
generativeAIService = GenerativeAIService(apiKey: apiKey, urlSession: urlSession)
self.generationConfig = generationConfig
self.safetySettings = safetySettings
self.tools = tools
self.toolConfig = toolConfig
self.systemInstruction = systemInstruction
self.requestOptions = requestOptions
Logging.default.info("""
[GoogleGenerativeAI] Model \(
name,
privacy: .public
) initialized. To enable additional logging, add \
`\(Logging.enableArgumentKey, privacy: .public)` as a launch argument in Xcode.
""")
Logging.verbose.debug("[GoogleGenerativeAI] Verbose logging enabled.")
}
/// Generates content from String and/or image inputs, given to the model as a prompt, that are
/// representable as one or more ``ModelContent/Part``s.
///
/// Since ``ModelContent/Part``s do not specify a role, this method is intended for generating
/// content from
/// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
/// or "direct" prompts. For
/// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
/// prompts, see `generateContent(_ content: @autoclosure () throws -> [ModelContent])`.
///
/// - Parameter content: The input(s) given to the model as a prompt (see
/// ``ThrowingPartsRepresentable``
/// for conforming types).
/// - Returns: The content generated by the model.
/// - Throws: A ``GenerateContentError`` if the request failed.
public func generateContent(_ parts: any ThrowingPartsRepresentable...)
async throws -> GenerateContentResponse {
return try await generateContent([ModelContent(parts: parts)])
}
/// Generates new content from input content given to the model as a prompt.
///
/// - Parameter content: The input(s) given to the model as a prompt.
/// - Returns: The generated content response from the model.
/// - Throws: A ``GenerateContentError`` if the request failed.
public func generateContent(_ content: @autoclosure () throws -> [ModelContent]) async throws
-> GenerateContentResponse {
let response: GenerateContentResponse
do {
let generateContentRequest = try GenerateContentRequest(model: modelResourceName,
contents: content(),
generationConfig: generationConfig,
safetySettings: safetySettings,
tools: tools,
toolConfig: toolConfig,
systemInstruction: systemInstruction,
isStreaming: false,
options: requestOptions)
response = try await generativeAIService.loadRequest(request: generateContentRequest)
} catch {
if let imageError = error as? ImageConversionError {
throw GenerateContentError.promptImageContentError(underlying: imageError)
}
throw GenerativeModel.generateContentError(from: error)
}
// Check the prompt feedback to see if the prompt was blocked.
if response.promptFeedback?.blockReason != nil {
throw GenerateContentError.promptBlocked(response: response)
}
// Check to see if an error should be thrown for stop reason.
if let reason = response.candidates.first?.finishReason, reason != .stop {
throw GenerateContentError.responseStoppedEarly(reason: reason, response: response)
}
return response
}
/// Generates content from String and/or image inputs, given to the model as a prompt, that are
/// representable as one or more ``ModelContent/Part``s.
///
/// Since ``ModelContent/Part``s do not specify a role, this method is intended for generating
/// content from
/// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
/// or "direct" prompts. For
/// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
/// prompts, see `generateContent(_ content: @autoclosure () throws -> [ModelContent])`.
///
/// - Parameter content: The input(s) given to the model as a prompt (see
/// ``ThrowingPartsRepresentable``
/// for conforming types).
/// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
/// error if an error occurred.
@available(macOS 12.0, *)
public func generateContentStream(_ parts: any ThrowingPartsRepresentable...)
-> AsyncThrowingStream<GenerateContentResponse, Error> {
return try generateContentStream([ModelContent(parts: parts)])
}
/// Generates new content from input content given to the model as a prompt.
///
/// - Parameter content: The input(s) given to the model as a prompt.
/// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
/// error if an error occurred.
@available(macOS 12.0, *)
public func generateContentStream(_ content: @autoclosure () throws -> [ModelContent])
-> AsyncThrowingStream<GenerateContentResponse, Error> {
let evaluatedContent: [ModelContent]
do {
evaluatedContent = try content()
} catch let underlying {
return AsyncThrowingStream { continuation in
let error: Error
if let contentError = underlying as? ImageConversionError {
error = GenerateContentError.promptImageContentError(underlying: contentError)
} else {
error = GenerateContentError.internalError(underlying: underlying)
}
continuation.finish(throwing: error)
}
}
let generateContentRequest = GenerateContentRequest(model: modelResourceName,
contents: evaluatedContent,
generationConfig: generationConfig,
safetySettings: safetySettings,
tools: tools,
toolConfig: toolConfig,
systemInstruction: systemInstruction,
isStreaming: true,
options: requestOptions)
var responseIterator = generativeAIService.loadRequestStream(request: generateContentRequest)
.makeAsyncIterator()
return AsyncThrowingStream {
let response: GenerateContentResponse?
do {
response = try await responseIterator.next()
} catch {
throw GenerativeModel.generateContentError(from: error)
}
// The responseIterator will return `nil` when it's done.
guard let response = response else {
// This is the end of the stream! Signal it by sending `nil`.
return nil
}
// Check the prompt feedback to see if the prompt was blocked.
if response.promptFeedback?.blockReason != nil {
throw GenerateContentError.promptBlocked(response: response)
}
// If the stream ended early unexpectedly, throw an error.
if let finishReason = response.candidates.first?.finishReason, finishReason != .stop {
throw GenerateContentError.responseStoppedEarly(reason: finishReason, response: response)
} else {
// Response was valid content, pass it along and continue.
return response
}
}
}
/// Creates a new chat conversation using this model with the provided history.
public func startChat(history: [ModelContent] = []) -> Chat {
return Chat(model: self, history: history)
}
/// Runs the model's tokenizer on String and/or image inputs that are representable as one or more
/// ``ModelContent/Part``s.
///
/// Since ``ModelContent/Part``s do not specify a role, this method is intended for tokenizing
/// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
/// or "direct" prompts. For
/// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
/// input, see `countTokens(_ content: @autoclosure () throws -> [ModelContent])`.
///
/// - Parameter content: The input(s) given to the model as a prompt (see
/// ``ThrowingPartsRepresentable``
/// for conforming types).
/// - Returns: The results of running the model's tokenizer on the input; contains
/// ``CountTokensResponse/totalTokens``.
/// - Throws: A ``CountTokensError`` if the tokenization request failed.
public func countTokens(_ parts: any ThrowingPartsRepresentable...) async throws
-> CountTokensResponse {
return try await countTokens([ModelContent(parts: parts)])
}
/// Runs the model's tokenizer on the input content and returns the token count.
///
/// - Parameter content: The input given to the model as a prompt.
/// - Returns: The results of running the model's tokenizer on the input; contains
/// ``CountTokensResponse/totalTokens``.
/// - Throws: A ``CountTokensError`` if the tokenization request failed or the input content was
/// invalid.
public func countTokens(_ content: @autoclosure () throws -> [ModelContent]) async throws
-> CountTokensResponse {
do {
let generateContentRequest = try GenerateContentRequest(model: modelResourceName,
contents: content(),
generationConfig: generationConfig,
safetySettings: safetySettings,
tools: tools,
toolConfig: toolConfig,
systemInstruction: systemInstruction,
isStreaming: false,
options: requestOptions)
let countTokensRequest = CountTokensRequest(
model: modelResourceName,
generateContentRequest: generateContentRequest,
options: requestOptions
)
return try await generativeAIService.loadRequest(request: countTokensRequest)
} catch {
throw CountTokensError.internalError(underlying: error)
}
}
/// Returns a model resource name of the form "models/model-name" based on `name`.
private static func modelResourceName(name: String) -> String {
if name.contains("/") {
return name
} else {
return modelResourcePrefix + name
}
}
/// Returns a `GenerateContentError` (for public consumption) from an internal error.
///
/// If `error` is already a `GenerateContentError` the error is returned unchanged.
private static func generateContentError(from error: Error) -> GenerateContentError {
if let error = error as? GenerateContentError {
return error
} else if let error = error as? RPCError, error.isInvalidAPIKeyError() {
return GenerateContentError.invalidAPIKey(message: error.message)
} else if let error = error as? RPCError, error.isUnsupportedUserLocationError() {
return GenerateContentError.unsupportedUserLocation
}
return GenerateContentError.internalError(underlying: error)
}
}
/// An error thrown in `GenerativeModel.countTokens(_:)`.
@available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
public enum CountTokensError: Error {
case internalError(underlying: Error)
}