-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathgenerative_models.ts
More file actions
583 lines (557 loc) · 19.3 KB
/
generative_models.ts
File metadata and controls
583 lines (557 loc) · 19.3 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/**
* @license
* 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
*
* https://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.
*/
/* tslint:disable */
import {GoogleAuth} from 'google-auth-library';
import {formulateSystemInstructionIntoContent} from '../functions/util';
import {countTokens} from '../functions/count_tokens';
import {
generateContent,
generateContentStream,
} from '../functions/generate_content';
import {
CachedContent,
Content,
CountTokensRequest,
CountTokensResponse,
GenerateContentRequest,
GenerateContentResult,
GenerationConfig,
GetGenerativeModelParams,
RequestOptions,
SafetySetting,
StartChatParams,
StartChatSessionRequest,
StreamGenerateContentResult,
Tool,
} from '../types/content';
import {ToolConfig} from '../types/tool';
import {ClientError, GoogleAuthError} from '../types/errors';
import {constants} from '../util';
import {ChatSession, ChatSessionPreview} from './chat_session';
/**
* The `GenerativeModel` class is the base class for the generative models on
* Vertex AI.
* NOTE: Don't instantiate this class directly. Use
* `vertexai.getGenerativeModel()` instead.
*/
export class GenerativeModel {
private readonly model: string;
private readonly generationConfig?: GenerationConfig;
private readonly safetySettings?: SafetySetting[];
private readonly tools?: Tool[];
private readonly toolConfig?: ToolConfig;
private readonly requestOptions?: RequestOptions;
private readonly systemInstruction?: Content;
private readonly project: string;
private readonly location: string;
private readonly googleAuth: GoogleAuth;
private readonly publisherModelEndpoint: string;
private readonly resourcePath: string;
private readonly apiEndpoint?: string;
/**
* @constructor
* @param getGenerativeModelParams - {@link GetGenerativeModelParams}
*/
constructor(getGenerativeModelParams: GetGenerativeModelParams) {
this.project = getGenerativeModelParams.project;
this.location = getGenerativeModelParams.location;
this.apiEndpoint = getGenerativeModelParams.apiEndpoint;
this.googleAuth = getGenerativeModelParams.googleAuth;
this.model = getGenerativeModelParams.model;
this.generationConfig = getGenerativeModelParams.generationConfig;
this.safetySettings = getGenerativeModelParams.safetySettings;
this.tools = getGenerativeModelParams.tools;
this.toolConfig = getGenerativeModelParams.toolConfig;
this.requestOptions = getGenerativeModelParams.requestOptions ?? {};
if (getGenerativeModelParams.systemInstruction) {
this.systemInstruction = formulateSystemInstructionIntoContent(
getGenerativeModelParams.systemInstruction
);
}
this.resourcePath = formulateResourcePathFromModel(
this.model,
this.project,
this.location
);
// publisherModelEndpoint is deprecated
this.publisherModelEndpoint = this.resourcePath;
}
/**
* Gets access token from GoogleAuth. Throws {@link GoogleAuthError} when
* fails.
* @returns Promise of token string.
*/
private fetchToken(): Promise<string | null | undefined> {
const tokenPromise = this.googleAuth.getAccessToken().catch(e => {
throw new GoogleAuthError(constants.CREDENTIAL_ERROR_MESSAGE, e);
});
return tokenPromise;
}
/**
* Makes an async call to generate content.
*
* The response will be returned in {@link
* GenerateContentResult.response}.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const result = await generativeModel.generateContent(request);
* console.log('Response: ', JSON.stringify(result.response));
* ```
*
* @param request - A GenerateContentRequest object with the request contents.
* @returns The GenerateContentResponse object with the response candidates.
*/
async generateContent(
request: GenerateContentRequest | string
): Promise<GenerateContentResult> {
request = formulateRequestToGenerateContentRequest(request);
const formulatedRequest =
formulateSystemInstructionIntoGenerateContentRequest(
request,
this.systemInstruction
);
return generateContent(
this.location,
this.resourcePath,
this.fetchToken(),
formulatedRequest,
this.apiEndpoint,
this.generationConfig,
this.safetySettings,
this.tools,
this.toolConfig,
this.requestOptions
);
}
/**
* Makes an async stream request to generate content.
*
* The response is returned chunk by chunk as it's being generated in {@link
* StreamGenerateContentResult.stream}. After all chunks of the response are
* returned, the aggregated response is available in
* {@link StreamGenerateContentResult.response}.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const streamingResult = await generativeModel.generateContentStream(request);
* for await (const item of streamingResult.stream) {
* console.log('stream chunk: ', JSON.stringify(item));
* }
* const aggregatedResponse = await streamingResult.response;
* console.log('aggregated response: ', JSON.stringify(aggregatedResponse));
* ```
*
* @param request - {@link GenerateContentRequest}
* @returns Promise of {@link StreamGenerateContentResult}
*/
async generateContentStream(
request: GenerateContentRequest | string
): Promise<StreamGenerateContentResult> {
request = formulateRequestToGenerateContentRequest(request);
const formulatedRequest =
formulateSystemInstructionIntoGenerateContentRequest(
request,
this.systemInstruction
);
return generateContentStream(
this.location,
this.resourcePath,
this.fetchToken(),
formulatedRequest,
this.apiEndpoint,
this.generationConfig,
this.safetySettings,
this.tools,
this.toolConfig,
this.requestOptions
);
}
/**
* Makes an async request to count tokens.
*
* The `countTokens` function returns the token count and the number of
* billable characters for a prompt.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const resp = await generativeModel.countTokens(request);
* console.log('count tokens response: ', resp);
* ```
*
* @param request - A CountTokensRequest object with the request contents.
* @returns The CountTokensResponse object with the token count.
*/
async countTokens(request: CountTokensRequest): Promise<CountTokensResponse> {
return countTokens(
this.location,
this.resourcePath,
this.fetchToken(),
request,
this.apiEndpoint,
this.requestOptions
);
}
/**
* Instantiates a {@link ChatSession}.
*
* The {@link ChatSession} class is a stateful class that holds the state of
* the conversation with the model and provides methods to interact with the
* model in chat mode. Calling this method doesn't make any calls to a remote
* endpoint. To make remote call, use {@link ChatSession.sendMessage} or
* @link ChatSession.sendMessageStream}.
*
* @example
* ```
* const chat = generativeModel.startChat();
* const result1 = await chat.sendMessage("How can I learn more about Node.js?");
* const response1 = await result1.response;
* console.log('Response: ', JSON.stringify(response1));
*
* const result2 = await chat.sendMessageStream("What about python?");
* const response2 = await result2.response;
* console.log('Response: ', JSON.stringify(await response2));
* ```
*
* @param request - {@link StartChatParams}
* @returns {@link ChatSession}
*/
async startChat(request?: StartChatParams): Promise<ChatSession> {
const startChatRequest: StartChatSessionRequest = {
project: this.project,
location: this.location,
googleAuth: this.googleAuth,
publisherModelEndpoint: this.publisherModelEndpoint,
resourcePath: this.resourcePath,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
};
if (request) {
startChatRequest.history = request.history;
startChatRequest.generationConfig =
request.generationConfig ?? this.generationConfig;
startChatRequest.safetySettings =
request.safetySettings ?? this.safetySettings;
startChatRequest.tools = request.tools ?? this.tools;
startChatRequest.toolConfig = request.toolConfig ?? this.toolConfig;
startChatRequest.apiEndpoint = request.apiEndpoint ?? this.apiEndpoint;
startChatRequest.systemInstruction =
request.systemInstruction ?? this.systemInstruction;
}
await this.fetchToken();
return new ChatSession(startChatRequest, this.requestOptions);
}
}
/**
* The `GenerativeModelPreview` class is the base class for the generative models
* that are in preview.
* NOTE: Don't instantiate this class directly. Use
* `vertexai.preview.getGenerativeModel()` instead.
*/
export class GenerativeModelPreview {
private readonly model: string;
private readonly generationConfig?: GenerationConfig;
private readonly safetySettings?: SafetySetting[];
private readonly tools?: Tool[];
private readonly toolConfig?: ToolConfig;
private readonly requestOptions?: RequestOptions;
private readonly systemInstruction?: Content;
private readonly project: string;
private readonly location: string;
private readonly googleAuth: GoogleAuth;
private readonly publisherModelEndpoint: string;
private readonly resourcePath: string;
private readonly apiEndpoint?: string;
private readonly cachedContent?: CachedContent;
/**
* @constructor
* @param getGenerativeModelParams - {@link GetGenerativeModelParams}
*/
constructor(getGenerativeModelParams: GetGenerativeModelParams) {
this.project = getGenerativeModelParams.project;
this.location = getGenerativeModelParams.location;
this.apiEndpoint = getGenerativeModelParams.apiEndpoint;
this.googleAuth = getGenerativeModelParams.googleAuth;
this.model = getGenerativeModelParams.model;
this.generationConfig = getGenerativeModelParams.generationConfig;
this.safetySettings = getGenerativeModelParams.safetySettings;
this.tools = getGenerativeModelParams.tools;
this.toolConfig = getGenerativeModelParams.toolConfig;
this.cachedContent = getGenerativeModelParams.cachedContent;
this.requestOptions = getGenerativeModelParams.requestOptions ?? {};
if (getGenerativeModelParams.systemInstruction) {
this.systemInstruction = formulateSystemInstructionIntoContent(
getGenerativeModelParams.systemInstruction
);
}
this.resourcePath = formulateResourcePathFromModel(
this.model,
this.project,
this.location
);
// publisherModelEndpoint is deprecated
this.publisherModelEndpoint = this.resourcePath;
}
/**
* Gets access token from GoogleAuth. Throws {@link GoogleAuthError} when
* fails.
* @returns Promise of token string.
*/
private fetchToken(): Promise<string | null | undefined> {
const tokenPromise = this.googleAuth.getAccessToken().catch(e => {
throw new GoogleAuthError(constants.CREDENTIAL_ERROR_MESSAGE, e);
});
return tokenPromise;
}
/**
* Makes an async call to generate content.
*
* The response will be returned in {@link GenerateContentResult.response}.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const result = await generativeModelPreview.generateContent(request);
* console.log('Response: ', JSON.stringify(result.response));
* ```
*
* @param request - A GenerateContentRequest object with the request contents.
* @returns The GenerateContentResponse object with the response candidates.
*/
async generateContent(
request: GenerateContentRequest | string
): Promise<GenerateContentResult> {
request = formulateRequestToGenerateContentRequest(request);
const formulatedRequest = {
...formulateSystemInstructionIntoGenerateContentRequest(
request,
this.systemInstruction
),
cachedContent: this.cachedContent?.name,
};
return generateContent(
this.location,
this.resourcePath,
this.fetchToken(),
formulatedRequest,
this.apiEndpoint,
this.generationConfig,
this.safetySettings,
this.tools,
this.toolConfig,
this.requestOptions
);
}
/**
* Makes an async stream request to generate content.
*
* The response is returned chunk by chunk as it's being generated in {@link
* StreamGenerateContentResult.stream}. After all chunks of the response are
* returned, the aggregated response is available in
* {@link StreamGenerateContentResult.response}.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const streamingResult = await generativeModelPreview.generateContentStream(request);
* for await (const item of streamingResult.stream) {
* console.log('stream chunk: ', JSON.stringify(item));
* }
* const aggregatedResponse = await streamingResult.response;
* console.log('aggregated response: ', JSON.stringify(aggregatedResponse));
* ```
*
* @param request - {@link GenerateContentRequest}
* @returns Promise of {@link StreamGenerateContentResult}
*/
async generateContentStream(
request: GenerateContentRequest | string
): Promise<StreamGenerateContentResult> {
request = formulateRequestToGenerateContentRequest(request);
const formulatedRequest = {
...formulateSystemInstructionIntoGenerateContentRequest(
request,
this.systemInstruction
),
cachedContent: this.cachedContent?.name,
};
return generateContentStream(
this.location,
this.resourcePath,
this.fetchToken(),
formulatedRequest,
this.apiEndpoint,
this.generationConfig,
this.safetySettings,
this.tools,
this.toolConfig,
this.requestOptions
);
}
/**
* Makes an async request to count tokens.
*
* The `countTokens` function returns the token count and the number of
* billable characters for a prompt.
*
* @example
* ```
* const request = {
* contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
* };
* const resp = await generativeModelPreview.countTokens(request);
* console.log('count tokens response: ', resp);
* ```
*
* @param request - A CountTokensRequest object with the request contents.
* @returns The CountTokensResponse object with the token count.
*/
async countTokens(request: CountTokensRequest): Promise<CountTokensResponse> {
return countTokens(
this.location,
this.resourcePath,
this.fetchToken(),
request,
this.apiEndpoint,
this.requestOptions
);
}
/**
* Instantiates a {@link ChatSessionPreview}.
*
* The {@link ChatSessionPreview} class is a stateful class that holds the state of
* the conversation with the model and provides methods to interact with the
* model in chat mode. Calling this method doesn't make any calls to a remote
* endpoint. To make remote call, use {@link ChatSessionPreview.sendMessage} or
* {@link ChatSessionPreview.sendMessageStream}.
*
* @example
* ```
* const chat = generativeModelPreview.startChat();
* const result1 = await chat.sendMessage("How can I learn more about Node.js?");
* const response1 = await result1.response;
* console.log('Response: ', JSON.stringify(response1));
*
* const result2 = await chat.sendMessageStream("What about python?");
* const response2 = await result2.response;
* console.log('Response: ', JSON.stringify(await response2));
* ```
*
* @param request - {@link StartChatParams}
* @returns {@link ChatSessionPreview}
*/
startChat(request?: StartChatParams): ChatSessionPreview {
const startChatRequest: StartChatSessionRequest = {
project: this.project,
location: this.location,
googleAuth: this.googleAuth,
publisherModelEndpoint: this.publisherModelEndpoint,
resourcePath: this.resourcePath,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
};
if (request) {
startChatRequest.history = request.history;
startChatRequest.generationConfig =
request.generationConfig ?? this.generationConfig;
startChatRequest.safetySettings =
request.safetySettings ?? this.safetySettings;
startChatRequest.tools = request.tools ?? this.tools;
startChatRequest.toolConfig = request.toolConfig ?? this.toolConfig;
startChatRequest.systemInstruction =
request.systemInstruction ?? this.systemInstruction;
startChatRequest.cachedContent =
request.cachedContent ?? this.cachedContent?.name;
}
return new ChatSessionPreview(startChatRequest, this.requestOptions);
}
getModelName(): string {
return this.model;
}
getCachedContent(): CachedContent | undefined {
return this.cachedContent;
}
getSystemInstruction(): Content | undefined {
return this.systemInstruction;
}
}
function formulateResourcePathFromModel(
model: string,
project: string,
location: string
): string {
let resourcePath: string;
if (!model) {
throw new ClientError('model parameter must not be empty.');
}
if (!model.includes('/')) {
// example 'gemini-1.0-pro'
resourcePath = `projects/${project}/locations/${location}/publishers/google/models/${model}`;
} else if (model.startsWith('models/')) {
// example 'models/gemini-1.0-pro'
resourcePath = `projects/${project}/locations/${location}/publishers/google/${model}`;
} else if (model.startsWith('projects/')) {
// example 'projects/my-project/locations/my-location/models/my-tuned-model'
resourcePath = model;
} else {
throw new ClientError(
'model parameter must be either a Model Garden model ID or a full resource name.'
);
}
return resourcePath;
}
function formulateRequestToGenerateContentRequest(
request: GenerateContentRequest | string
): GenerateContentRequest {
if (typeof request === 'string') {
return {
contents: [{role: constants.USER_ROLE, parts: [{text: request}]}],
} as GenerateContentRequest;
}
return request;
}
function formulateSystemInstructionIntoGenerateContentRequest(
methodRequest: GenerateContentRequest,
classSystemInstruction?: Content
): GenerateContentRequest {
if (methodRequest.systemInstruction) {
methodRequest.systemInstruction = formulateSystemInstructionIntoContent(
methodRequest.systemInstruction
);
return methodRequest;
}
if (classSystemInstruction) {
methodRequest.systemInstruction = classSystemInstruction;
}
return methodRequest;
}