-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathgenerative_model.dart
More file actions
272 lines (261 loc) · 9.02 KB
/
generative_model.dart
File metadata and controls
272 lines (261 loc) · 9.02 KB
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
// Copyright 2024 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.
// ignore_for_file: use_late_for_private_fields_and_variables
part of 'base_model.dart';
/// A multimodel generative model (like Gemini).
///
/// Allows generating content and counting the number of
/// tokens in a piece of content.
final class GenerativeModel extends BaseApiClientModel {
/// Create a [GenerativeModel] backed by the generative model named [model].
///
/// The [model] argument can be a model name (such as `'gemini-pro'`) or a
/// model code (such as `'models/gemini-pro'`).
/// There is no creation time check for whether the `model` string identifies
/// a known and supported model. If not, attempts to generate content
/// will fail.
///
/// The optional [safetySettings] and [generationConfig] can be used to
/// control and guide the generation. See [SafetySetting] and
/// [GenerationConfig] for details.
///
GenerativeModel._({
required String model,
required String location,
required FirebaseApp app,
required bool useVertexBackend,
bool? useLimitedUseAppCheckTokens,
FirebaseAppCheck? appCheck,
FirebaseAuth? auth,
List<SafetySetting>? safetySettings,
GenerationConfig? generationConfig,
this.tools,
ToolConfig? toolConfig,
Content? systemInstruction,
http.Client? httpClient,
}) : _safetySettings = safetySettings ?? [],
_generationConfig = generationConfig,
_toolConfig = toolConfig,
_systemInstruction = systemInstruction,
super(
serializationStrategy: useVertexBackend
? VertexSerialization()
: DeveloperSerialization(),
modelUri: useVertexBackend
? _VertexUri(app: app, model: model, location: location)
: _GoogleAIUri(app: app, model: model),
client: HttpApiClient(
apiKey: app.options.apiKey,
httpClient: httpClient,
requestHeaders: BaseModel.firebaseTokens(
appCheck, auth, app, useLimitedUseAppCheckTokens)));
GenerativeModel._constructTestModel({
required String model,
required String location,
required FirebaseApp app,
required useVertexBackend,
bool? useLimitedUseAppCheckTokens,
FirebaseAppCheck? appCheck,
FirebaseAuth? auth,
List<SafetySetting>? safetySettings,
GenerationConfig? generationConfig,
this.tools,
ToolConfig? toolConfig,
Content? systemInstruction,
ApiClient? apiClient,
}) : _safetySettings = safetySettings ?? [],
_generationConfig = generationConfig,
_toolConfig = toolConfig,
_systemInstruction = systemInstruction,
super(
serializationStrategy: useVertexBackend
? VertexSerialization()
: DeveloperSerialization(),
modelUri: useVertexBackend
? _VertexUri(app: app, model: model, location: location)
: _GoogleAIUri(app: app, model: model),
client: apiClient ??
HttpApiClient(
apiKey: app.options.apiKey,
requestHeaders: BaseModel.firebaseTokens(
appCheck, auth, app, useLimitedUseAppCheckTokens)));
final List<SafetySetting> _safetySettings;
final GenerationConfig? _generationConfig;
/// List of [Tool] registered in the model
final List<Tool>? tools;
final ToolConfig? _toolConfig;
final Content? _systemInstruction;
/// Generates content responding to [prompt].
///
/// Sends a "generateContent" API request for the configured model,
/// and waits for the response.
///
/// Example:
/// ```dart
/// final response = await model.generateContent([Content.text(prompt)]);
/// print(response.text);
/// ```
Future<GenerateContentResponse> generateContent(Iterable<Content> prompt,
{List<SafetySetting>? safetySettings,
GenerationConfig? generationConfig,
List<Tool>? tools,
ToolConfig? toolConfig}) {
final resolvedTools = tools ?? this.tools;
if (resolvedTools != null) {
Tool.validateToolCombination(resolvedTools);
}
return makeRequest(
Task.generateContent,
_serializationStrategy.generateContentRequest(
prompt,
model,
safetySettings ?? _safetySettings,
generationConfig ?? _generationConfig,
resolvedTools,
toolConfig ?? _toolConfig,
_systemInstruction,
),
_serializationStrategy.parseGenerateContentResponse);
}
/// Generates a stream of content responding to [prompt].
///
/// Sends a "streamGenerateContent" API request for the configured model,
/// and waits for the response.
///
/// Example:
/// ```dart
/// final responses = await model.generateContent([Content.text(prompt)]);
/// await for (final response in responses) {
/// print(response.text);
/// }
/// ```
Stream<GenerateContentResponse> generateContentStream(
Iterable<Content> prompt,
{List<SafetySetting>? safetySettings,
GenerationConfig? generationConfig,
List<Tool>? tools,
ToolConfig? toolConfig}) {
final resolvedTools = tools ?? this.tools;
if (resolvedTools != null) {
Tool.validateToolCombination(resolvedTools);
}
final response = client.streamRequest(
taskUri(Task.streamGenerateContent),
_serializationStrategy.generateContentRequest(
prompt,
model,
safetySettings ?? _safetySettings,
generationConfig ?? _generationConfig,
resolvedTools,
toolConfig ?? _toolConfig,
_systemInstruction,
));
return response.map(_serializationStrategy.parseGenerateContentResponse);
}
/// Counts the total number of tokens in [contents].
///
/// Sends a "countTokens" API request for the configured model,
/// and waits for the response.
///
/// Example:
/// ```dart
/// final promptContent = [Content.text(prompt)];
/// final totalTokens =
/// (await model.countTokens(promptContent)).totalTokens;
/// if (totalTokens > maxPromptSize) {
/// print('Prompt is too long!');
/// } else {
/// final response = await model.generateContent(promptContent);
/// print(response.text);
/// }
/// ```
Future<CountTokensResponse> countTokens(
Iterable<Content> contents,
) async {
if (tools != null) {
Tool.validateToolCombination(tools!);
}
final parameters = _serializationStrategy.countTokensRequest(
contents,
model,
_safetySettings,
_generationConfig,
tools,
_toolConfig,
);
return makeRequest(Task.countTokens, parameters,
_serializationStrategy.parseCountTokensResponse);
}
}
/// Returns a [GenerativeModel] using it's private constructor.
GenerativeModel createGenerativeModel({
required FirebaseApp app,
required String location,
required String model,
required bool useVertexBackend,
bool? useLimitedUseAppCheckTokens,
FirebaseAppCheck? appCheck,
FirebaseAuth? auth,
GenerationConfig? generationConfig,
List<SafetySetting>? safetySettings,
List<Tool>? tools,
ToolConfig? toolConfig,
Content? systemInstruction,
}) =>
GenerativeModel._(
model: model,
app: app,
appCheck: appCheck,
useVertexBackend: useVertexBackend,
useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens,
auth: auth,
location: location,
safetySettings: safetySettings,
generationConfig: generationConfig,
tools: tools,
toolConfig: toolConfig,
systemInstruction: systemInstruction,
);
/// Creates a model with an overridden [ApiClient] for testing.
///
/// Package private test-only method.
GenerativeModel createModelWithClient({
required FirebaseApp app,
required String location,
required String model,
required ApiClient client,
required bool useVertexBackend,
bool? useLimitedUseAppCheckTokens,
Content? systemInstruction,
FirebaseAppCheck? appCheck,
FirebaseAuth? auth,
GenerationConfig? generationConfig,
List<SafetySetting>? safetySettings,
List<Tool>? tools,
ToolConfig? toolConfig,
}) =>
GenerativeModel._constructTestModel(
model: model,
app: app,
appCheck: appCheck,
useVertexBackend: useVertexBackend,
useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens,
auth: auth,
location: location,
safetySettings: safetySettings,
generationConfig: generationConfig,
systemInstruction: systemInstruction,
tools: tools,
toolConfig: toolConfig,
apiClient: client);