/
_language_models.py
1208 lines (991 loc) · 43.3 KB
/
_language_models.py
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
#
"""Classes for working with language models."""
import dataclasses
from typing import Any, Dict, List, Optional, Sequence, Union
import warnings
from google.cloud import aiplatform
from google.cloud.aiplatform import base
from google.cloud.aiplatform import initializer as aiplatform_initializer
from google.cloud.aiplatform import utils as aiplatform_utils
from google.cloud.aiplatform.utils import gcs_utils
from vertexai._model_garden import _model_garden_models
try:
import pandas
except ImportError:
pandas = None
_LOGGER = base.Logger(__name__)
# Endpoint label/metadata key to preserve the base model ID information
_TUNING_BASE_MODEL_ID_LABEL_KEY = "google-vertex-llm-tuning-base-model-id"
def _get_model_id_from_tuning_model_id(tuning_model_id: str) -> str:
"""Gets the base model ID for the model ID labels used the tuned models.
Args:
tuning_model_id: The model ID used in tuning. E.g. `text-bison-001`
Returns:
The publisher model ID
Raises:
ValueError: If tuning model ID is unsupported
"""
model_name, _, version = tuning_model_id.rpartition("-")
# "publishers/google/models/text-bison@001"
return f"publishers/google/models/{model_name}@{version}"
class _LanguageModel(_model_garden_models._ModelGardenModel):
"""_LanguageModel is a base class for all language models."""
def __init__(self, model_id: str, endpoint_name: Optional[str] = None):
"""Creates a LanguageModel.
This constructor should not be called directly.
Use `LanguageModel.from_pretrained(model_name=...)` instead.
Args:
model_id: Identifier of a Vertex LLM. Example: "text-bison@001"
endpoint_name: Vertex Endpoint resource name for the model
"""
super().__init__(
model_id=model_id,
endpoint_name=endpoint_name,
)
@property
def _model_resource_name(self) -> str:
"""Full resource name of the model."""
if "publishers/" in self._endpoint_name:
return self._endpoint_name
else:
# This is a ModelRegistry resource name
return self._endpoint.list_models()[0].model
class _TunableModelMixin(_LanguageModel):
"""Model that can be tuned."""
def list_tuned_model_names(self) -> Sequence[str]:
"""Lists the names of tuned models.
Returns:
A list of tuned models that can be used with the `get_tuned_model` method.
"""
model_info = _model_garden_models._get_model_info(
model_id=self._model_id,
schema_to_class_map={self._INSTANCE_SCHEMA_URI: type(self)},
)
return _list_tuned_model_names(model_id=model_info.tuning_model_id)
@classmethod
def get_tuned_model(cls, tuned_model_name: str) -> "_LanguageModel":
"""Loads the specified tuned language model."""
tuned_vertex_model = aiplatform.Model(tuned_model_name)
tuned_model_labels = tuned_vertex_model.labels
if _TUNING_BASE_MODEL_ID_LABEL_KEY not in tuned_model_labels:
raise ValueError(
f"The provided model {tuned_model_name} does not have a base model ID."
)
tuning_model_id = tuned_vertex_model.labels[_TUNING_BASE_MODEL_ID_LABEL_KEY]
tuned_model_deployments = tuned_vertex_model.gca_resource.deployed_models
if len(tuned_model_deployments) == 0:
# Deploying the model
endpoint_name = tuned_vertex_model.deploy().resource_name
else:
endpoint_name = tuned_model_deployments[0].endpoint
base_model_id = _get_model_id_from_tuning_model_id(tuning_model_id)
model_info = _model_garden_models._get_model_info(
model_id=base_model_id,
schema_to_class_map={cls._INSTANCE_SCHEMA_URI: cls},
)
cls._validate_launch_stage(cls, model_info.publisher_model_resource)
model = model_info.interface_class(
model_id=base_model_id,
endpoint_name=endpoint_name,
)
return model
def tune_model(
self,
training_data: Union[str, "pandas.core.frame.DataFrame"],
*,
train_steps: int = 1000,
learning_rate: Optional[float] = None,
tuning_job_location: Optional[str] = None,
tuned_model_location: Optional[str] = None,
model_display_name: Optional[str] = None,
):
"""Tunes a model based on training data.
This method launches a model tuning job that can take some time.
Args:
training_data: A Pandas DataFrame or a URI pointing to data in JSON lines format.
The dataset schema is model-specific.
See https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#dataset_format
train_steps: Number of training batches to tune on (batch size is 8 samples).
learning_rate: Learning rate for the tuning
tuning_job_location: GCP location where the tuning job should be run.
Only "europe-west4" and "us-central1" locations are supported for now.
tuned_model_location: GCP location where the tuned model should be deployed. Only "us-central1" is supported for now.
model_display_name: Custom display name for the tuned model.
Returns:
A `LanguageModelTuningJob` object that represents the tuning job.
Calling `job.result()` blocks until the tuning is complete and returns a `LanguageModel` object.
Raises:
ValueError: If the "tuning_job_location" value is not supported
ValueError: If the "tuned_model_location" value is not supported
RuntimeError: If the model does not support tuning
"""
if tuning_job_location not in _TUNING_LOCATIONS:
raise ValueError(
"Please specify the tuning job location (`tuning_job_location`)."
f"Tuning is supported in the following locations: {_TUNING_LOCATIONS}"
)
if tuned_model_location != _TUNED_MODEL_LOCATION:
raise ValueError(
f'Model deployment is only supported in the following locations: tuned_model_location="{_TUNED_MODEL_LOCATION}"'
)
model_info = _model_garden_models._get_model_info(
model_id=self._model_id,
schema_to_class_map={self._INSTANCE_SCHEMA_URI: type(self)},
)
if not model_info.tuning_pipeline_uri:
raise RuntimeError(f"The {self._model_id} model does not support tuning")
pipeline_job = _launch_tuning_job(
training_data=training_data,
train_steps=train_steps,
model_id=model_info.tuning_model_id,
tuning_pipeline_uri=model_info.tuning_pipeline_uri,
model_display_name=model_display_name,
learning_rate=learning_rate,
tuning_job_location=tuning_job_location,
)
job = _LanguageModelTuningJob(
base_model=self,
job=pipeline_job,
)
self._job = job
tuned_model = job.result()
# The UXR study attendees preferred to tune model in place
self._endpoint = tuned_model._endpoint
self._endpoint_name = tuned_model._endpoint_name
@dataclasses.dataclass
class TextGenerationResponse:
"""TextGenerationResponse represents a response of a language model.
Attributes:
text: The generated text
is_blocked: Whether the the request was blocked.
safety_attributes: Scores for safety attributes.
Learn more about the safety attributes here:
https://cloud.google.com/vertex-ai/docs/generative-ai/learn/responsible-ai#safety_attribute_descriptions
"""
text: str
_prediction_response: Any
is_blocked: bool = False
safety_attributes: Dict[str, float] = dataclasses.field(default_factory=dict)
def __repr__(self):
return self.text
class _TextGenerationModel(_LanguageModel):
"""TextGenerationModel represents a general language model.
Examples::
# Getting answers:
model = TextGenerationModel.from_pretrained("text-bison@001")
model.predict("What is life?")
"""
_LAUNCH_STAGE = _model_garden_models._SDK_GA_LAUNCH_STAGE
_INSTANCE_SCHEMA_URI = "gs://google-cloud-aiplatform/schema/predict/instance/text_generation_1.0.0.yaml"
_DEFAULT_MAX_OUTPUT_TOKENS = 128
def predict(
self,
prompt: str,
*,
max_output_tokens: Optional[int] = _DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> "TextGenerationResponse":
"""Gets model response for a single prompt.
Args:
prompt: Question to ask the model.
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
Returns:
A `TextGenerationResponse` object that contains the text produced by the model.
"""
return self._batch_predict(
prompts=[prompt],
max_output_tokens=max_output_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
)[0]
def _batch_predict(
self,
prompts: List[str],
max_output_tokens: Optional[int] = _DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> List["TextGenerationResponse"]:
"""Gets model response for a single prompt.
Args:
prompts: Questions to ask the model.
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
Returns:
A list of `TextGenerationResponse` objects that contain the texts produced by the model.
"""
instances = [{"content": str(prompt)} for prompt in prompts]
prediction_parameters = {}
if max_output_tokens:
prediction_parameters["maxDecodeSteps"] = max_output_tokens
if temperature is not None:
prediction_parameters["temperature"] = temperature
if top_p:
prediction_parameters["topP"] = top_p
if top_k:
prediction_parameters["topK"] = top_k
prediction_response = self._endpoint.predict(
instances=instances,
parameters=prediction_parameters,
)
results = []
for prediction in prediction_response.predictions:
safety_attributes_dict = prediction.get("safetyAttributes", {})
results.append(
TextGenerationResponse(
text=prediction["content"],
_prediction_response=prediction_response,
is_blocked=safety_attributes_dict.get("blocked", False),
safety_attributes=dict(
zip(
safety_attributes_dict.get("categories", []),
safety_attributes_dict.get("scores", []),
)
),
)
)
return results
class _ModelWithBatchPredict(_LanguageModel):
"""Model that supports batch prediction."""
def batch_predict(
self,
*,
dataset: Union[str, List[str]],
destination_uri_prefix: str,
model_parameters: Optional[Dict] = None,
) -> aiplatform.BatchPredictionJob:
"""Starts a batch prediction job with the model.
Args:
dataset: The location of the dataset.
`gs://` and `bq://` URIs are supported.
destination_uri_prefix: The URI prefix for the prediction.
`gs://` and `bq://` URIs are supported.
model_parameters: Model-specific parameters to send to the model.
Returns:
A `BatchPredictionJob` object
Raises:
ValueError: When source or destination URI is not supported.
"""
arguments = {}
first_source_uri = dataset if isinstance(dataset, str) else dataset[0]
if first_source_uri.startswith("gs://"):
if not isinstance(dataset, str):
if not all(uri.startswith("gs://") for uri in dataset):
raise ValueError(
f"All URIs in the list must start with 'gs://': {dataset}"
)
arguments["gcs_source"] = dataset
elif first_source_uri.startswith("bq://"):
if not isinstance(dataset, str):
raise ValueError(
f"Only single BigQuery source can be specified: {dataset}"
)
arguments["bigquery_source"] = dataset
else:
raise ValueError(f"Unsupported source_uri: {dataset}")
if destination_uri_prefix.startswith("gs://"):
arguments["gcs_destination_prefix"] = destination_uri_prefix
elif destination_uri_prefix.startswith("bq://"):
arguments["bigquery_destination_prefix"] = destination_uri_prefix
else:
raise ValueError(f"Unsupported destination_uri: {destination_uri_prefix}")
model_name = self._model_resource_name
# TODO(b/284512065): Batch prediction service does not support
# fully qualified publisher model names yet
publishers_index = model_name.index("/publishers/")
if publishers_index > 0:
model_name = model_name[publishers_index + 1 :]
job = aiplatform.BatchPredictionJob.create(
model_name=model_name,
job_display_name=None,
**arguments,
model_parameters=model_parameters,
)
return job
class _PreviewModelWithBatchPredict(_ModelWithBatchPredict):
"""Model that supports batch prediction."""
def batch_predict(
self,
*,
destination_uri_prefix: str,
dataset: Optional[Union[str, List[str]]] = None,
model_parameters: Optional[Dict] = None,
**_kwargs: Optional[Dict[str, Any]],
) -> aiplatform.BatchPredictionJob:
"""Starts a batch prediction job with the model.
Args:
dataset: Required. The location of the dataset.
`gs://` and `bq://` URIs are supported.
destination_uri_prefix: The URI prefix for the prediction.
`gs://` and `bq://` URIs are supported.
model_parameters: Model-specific parameters to send to the model.
**_kwargs: Deprecated.
Returns:
A `BatchPredictionJob` object
Raises:
ValueError: When source or destination URI is not supported.
"""
if "source_uri" in _kwargs:
warnings.warn("source_uri is deprecated, use dataset instead.")
if dataset:
raise ValueError("source_uri is deprecated, use dataset instead.")
dataset = _kwargs["source_uri"]
if not dataset:
raise ValueError("dataset must be specified")
return super().batch_predict(
dataset=dataset,
destination_uri_prefix=destination_uri_prefix,
model_parameters=model_parameters,
)
class TextGenerationModel(_TextGenerationModel, _ModelWithBatchPredict):
pass
class _PreviewTextGenerationModel(
_TextGenerationModel, _TunableModelMixin, _PreviewModelWithBatchPredict
):
# Do not add docstring so that it's inherited from the base class.
_LAUNCH_STAGE = _model_garden_models._SDK_PUBLIC_PREVIEW_LAUNCH_STAGE
class _ChatModel(_TextGenerationModel):
"""ChatModel represents a language model that is capable of chat.
Examples::
# Getting answers:
model = ChatModel.from_pretrained("chat-bison@001")
model.predict("What is life?")
# Chat:
chat = model.start_chat()
chat.send_message("Do you know any cool events this weekend?")
"""
def start_chat(
self,
max_output_tokens: int = _TextGenerationModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> "_ChatSession":
"""Starts a chat session with the model.
Args:
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
Returns:
A `ChatSession` object.
"""
return _ChatSession(
model=self,
max_output_tokens=max_output_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
)
class _ChatSession:
"""ChatSession represents a chat session with a language model.
Within a chat session, the model keeps context and remembers the previous conversation.
"""
def __init__(
self,
model: _ChatModel,
max_output_tokens: int = _TextGenerationModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
):
self._model = model
self._history = []
self._history_text = ""
self._max_output_tokens = max_output_tokens
self._temperature = temperature
self._top_k = top_k
self._top_p = top_p
def send_message(
self,
message: str,
*,
max_output_tokens: Optional[int] = None,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> "TextGenerationResponse":
"""Sends message to the language model and gets a response.
Args:
message: Message to send to the model
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
Uses the value specified when calling `ChatModel.start_chat` by default.
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
Uses the value specified when calling `ChatModel.start_chat` by default.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
Uses the value specified when calling `ChatModel.start_chat` by default.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
Uses the value specified when calling `ChatModel.start_chat` by default.
Returns:
A `TextGenerationResponse` object that contains the text produced by the model.
"""
new_history_text = ""
if self._history_text:
new_history_text = self._history_text.rstrip("\n") + "\n\n"
new_history_text += message.rstrip("\n") + "\n"
response_obj = self._model.predict(
prompt=new_history_text,
max_output_tokens=max_output_tokens
if max_output_tokens is not None
else self._max_output_tokens,
temperature=temperature if temperature is not None else self._temperature,
top_k=top_k if top_k is not None else self._top_k,
top_p=top_p if top_p is not None else self._top_p,
)
response_text = response_obj.text
self._history.append((message, response_text))
new_history_text += response_text.rstrip("\n") + "\n"
self._history_text = new_history_text
return response_obj
class TextEmbeddingModel(_LanguageModel):
"""TextEmbeddingModel converts text into a vector of floating-point numbers.
Examples::
# Getting embedding:
model = TextEmbeddingModel.from_pretrained("textembedding-gecko@001")
embeddings = model.get_embeddings(["What is life?"])
for embedding in embeddings:
vector = embedding.values
print(len(vector))
"""
_LAUNCH_STAGE = _model_garden_models._SDK_GA_LAUNCH_STAGE
_INSTANCE_SCHEMA_URI = (
"gs://google-cloud-aiplatform/schema/predict/instance/text_embedding_1.0.0.yaml"
)
def get_embeddings(self, texts: List[str]) -> List["TextEmbedding"]:
instances = [{"content": str(text)} for text in texts]
prediction_response = self._endpoint.predict(
instances=instances,
)
return [
TextEmbedding(
values=prediction["embeddings"]["values"],
_prediction_response=prediction_response,
)
for prediction in prediction_response.predictions
]
class _PreviewTextEmbeddingModel(TextEmbeddingModel, _ModelWithBatchPredict):
_LAUNCH_STAGE = _model_garden_models._SDK_PUBLIC_PREVIEW_LAUNCH_STAGE
class TextEmbedding:
"""Contains text embedding vector."""
def __init__(
self,
values: List[float],
_prediction_response: Any = None,
):
self.values = values
self._prediction_response = _prediction_response
@dataclasses.dataclass
class InputOutputTextPair:
"""InputOutputTextPair represents a pair of input and output texts."""
input_text: str
output_text: str
@dataclasses.dataclass
class ChatMessage:
"""A chat message.
Attributes:
content: Content of the message.
author: Author of the message.
"""
content: str
author: str
class _ChatModelBase(_LanguageModel):
"""_ChatModelBase is a base class for chat models."""
_LAUNCH_STAGE = _model_garden_models._SDK_GA_LAUNCH_STAGE
def start_chat(
self,
*,
context: Optional[str] = None,
examples: Optional[List[InputOutputTextPair]] = None,
max_output_tokens: Optional[int] = _TextGenerationModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
message_history: Optional[List[ChatMessage]] = None,
) -> "ChatSession":
"""Starts a chat session with the model.
Args:
context: Context shapes how the model responds throughout the conversation.
For example, you can use context to specify words the model can or cannot use, topics to focus on or avoid, or the response format or style
examples: List of structured messages to the model to learn how to respond to the conversation.
A list of `InputOutputTextPair` objects.
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
message_history: A list of previously sent and received messages.
Returns:
A `ChatSession` object.
"""
return ChatSession(
model=self,
context=context,
examples=examples,
max_output_tokens=max_output_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
message_history=message_history,
)
class ChatModel(_ChatModelBase):
"""ChatModel represents a language model that is capable of chat.
Examples::
chat_model = ChatModel.from_pretrained("chat-bison@001")
chat = chat_model.start_chat(
context="My name is Ned. You are my personal assistant. My favorite movies are Lord of the Rings and Hobbit.",
examples=[
InputOutputTextPair(
input_text="Who do you work for?",
output_text="I work for Ned.",
),
InputOutputTextPair(
input_text="What do I like?",
output_text="Ned likes watching movies.",
),
],
temperature=0.3,
)
chat.send_message("Do you know any cool events this weekend?")
"""
_INSTANCE_SCHEMA_URI = "gs://google-cloud-aiplatform/schema/predict/instance/chat_generation_1.0.0.yaml"
class _PreviewChatModel(ChatModel, _TunableModelMixin):
_LAUNCH_STAGE = _model_garden_models._SDK_PUBLIC_PREVIEW_LAUNCH_STAGE
class CodeChatModel(_ChatModelBase):
"""CodeChatModel represents a model that is capable of completing code.
Examples:
code_chat_model = CodeChatModel.from_pretrained("codechat-bison@001")
code_chat = code_chat_model.start_chat(
max_output_tokens=128,
temperature=0.2,
)
code_chat.send_message("Please help write a function to calculate the min of two numbers")
"""
_INSTANCE_SCHEMA_URI = "gs://google-cloud-aiplatform/schema/predict/instance/codechat_generation_1.0.0.yaml"
_LAUNCH_STAGE = _model_garden_models._SDK_GA_LAUNCH_STAGE
_DEFAULT_MAX_OUTPUT_TOKENS = 128
def start_chat(
self,
*,
max_output_tokens: Optional[int] = _DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
message_history: Optional[List[ChatMessage]] = None,
) -> "CodeChatSession":
"""Starts a chat session with the code chat model.
Args:
max_output_tokens: Max length of the output text in tokens. Range: [1, 1000].
temperature: Controls the randomness of predictions. Range: [0, 1].
Returns:
A `ChatSession` object.
"""
return CodeChatSession(
model=self,
max_output_tokens=max_output_tokens,
temperature=temperature,
message_history=message_history
)
class _PreviewCodeChatModel(CodeChatModel, _TunableModelMixin):
_LAUNCH_STAGE = _model_garden_models._SDK_PUBLIC_PREVIEW_LAUNCH_STAGE
class _ChatSessionBase:
"""_ChatSessionBase is a base class for all chat sessions."""
USER_AUTHOR = "user"
MODEL_AUTHOR = "bot"
def __init__(
self,
model: _ChatModelBase,
context: Optional[str] = None,
examples: Optional[List[InputOutputTextPair]] = None,
max_output_tokens: Optional[int] = _TextGenerationModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
message_history: Optional[List[ChatMessage]] = None,
):
self._model = model
self._context = context
self._examples = examples
self._max_output_tokens = max_output_tokens
self._temperature = temperature
self._top_k = top_k
self._top_p = top_p
self._message_history: List[ChatMessage] = message_history or []
@property
def message_history(self) -> List[ChatMessage]:
"""List of previous messages."""
return self._message_history
def send_message(
self,
message: str,
*,
max_output_tokens: Optional[int] = None,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> "TextGenerationResponse":
"""Sends message to the language model and gets a response.
Args:
message: Message to send to the model
max_output_tokens: Max length of the output text in tokens. Range: [1, 1024].
Uses the value specified when calling `ChatModel.start_chat` by default.
temperature: Controls the randomness of predictions. Range: [0, 1]. Default: 0.
Uses the value specified when calling `ChatModel.start_chat` by default.
top_k: The number of highest probability vocabulary tokens to keep for top-k-filtering. Range: [1, 40]. Default: 40.
Uses the value specified when calling `ChatModel.start_chat` by default.
top_p: The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Range: [0, 1]. Default: 0.95.
Uses the value specified when calling `ChatModel.start_chat` by default.
Returns:
A `TextGenerationResponse` object that contains the text produced by the model.
"""
prediction_parameters = {}
max_output_tokens = max_output_tokens or self._max_output_tokens
if max_output_tokens:
prediction_parameters["maxDecodeSteps"] = max_output_tokens
if temperature is None:
temperature = self._temperature
if temperature is not None:
prediction_parameters["temperature"] = temperature
top_p = top_p or self._top_p
if top_p:
prediction_parameters["topP"] = top_p
top_k = top_k or self._top_k
if top_k:
prediction_parameters["topK"] = top_k
message_structs = []
for past_message in self._message_history:
message_structs.append(
{
"author": past_message.author,
"content": past_message.content,
}
)
message_structs.append(
{
"author": self.USER_AUTHOR,
"content": message,
}
)
prediction_instance = {"messages": message_structs}
if self._context:
prediction_instance["context"] = self._context
if self._examples:
prediction_instance["examples"] = [
{
"input": {"content": example.input_text},
"output": {"content": example.output_text},
}
for example in self._examples
]
prediction_response = self._model._endpoint.predict(
instances=[prediction_instance],
parameters=prediction_parameters,
)
prediction = prediction_response.predictions[0]
# ! Note: For chat models, the safetyAttributes is a list.
safety_attributes = prediction["safetyAttributes"][0]
response_obj = TextGenerationResponse(
text=prediction["candidates"][0]["content"]
if prediction.get("candidates")
else None,
_prediction_response=prediction_response,
is_blocked=safety_attributes.get("blocked", False),
safety_attributes=dict(
zip(
safety_attributes.get("categories", []),
safety_attributes.get("scores", []),
)
),
)
response_text = response_obj.text
self._message_history.append(
ChatMessage(content=message, author=self.USER_AUTHOR)
)
self._message_history.append(
ChatMessage(content=response_text, author=self.MODEL_AUTHOR)
)
return response_obj
class ChatSession(_ChatSessionBase):
"""ChatSession represents a chat session with a language model.
Within a chat session, the model keeps context and remembers the previous conversation.
"""
def __init__(
self,
model: ChatModel,
context: Optional[str] = None,
examples: Optional[List[InputOutputTextPair]] = None,
max_output_tokens: Optional[int] = _TextGenerationModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
message_history: Optional[List[ChatMessage]] = None,
):
super().__init__(
model=model,
context=context,
examples=examples,
max_output_tokens=max_output_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
message_history=message_history,
)
class CodeChatSession(_ChatSessionBase):
"""CodeChatSession represents a chat session with code chat language model.
Within a code chat session, the model keeps context and remembers the previous converstion.
"""
def __init__(
self,
model: CodeChatModel,
max_output_tokens: int = CodeChatModel._DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
message_history: Optional[List[ChatMessage]] = None,
):
super().__init__(
model=model,
max_output_tokens=max_output_tokens,
temperature=temperature,
message_history=message_history,
)
def send_message(
self,
message: str,
*,
max_output_tokens: Optional[int] = None,
temperature: Optional[float] = None,
) -> "TextGenerationResponse":
"""Sends message to the code chat model and gets a response.
Args:
message: Message to send to the model
max_output_tokens: Max length of the output text in tokens. Range: [1, 1000].
Uses the value specified when calling `CodeChatModel.start_chat` by default.
temperature: Controls the randomness of predictions. Range: [0, 1].
Uses the value specified when calling `CodeChatModel.start_chat` by default.
Returns:
A `TextGenerationResponse` object that contains the text produced by the model.
"""
return super().send_message(
message=message,
max_output_tokens=max_output_tokens,
temperature=temperature,
)
class CodeGenerationModel(_LanguageModel):
"""A language model that generates code.
Examples:
# Getting answers:
generation_model = CodeGenerationModel.from_pretrained("code-bison@001")
print(generation_model.predict(
prefix="Write a function that checks if a year is a leap year.",
))
completion_model = CodeGenerationModel.from_pretrained("code-gecko@001")
print(completion_model.predict(
prefix="def reverse_string(s):",
))
"""
_INSTANCE_SCHEMA_URI = "gs://google-cloud-aiplatform/schema/predict/instance/code_generation_1.0.0.yaml"
_LAUNCH_STAGE = _model_garden_models._SDK_GA_LAUNCH_STAGE
_DEFAULT_MAX_OUTPUT_TOKENS = 128
def predict(
self,
prefix: str,
suffix: Optional[str] = None,
*,
max_output_tokens: Optional[int] = _DEFAULT_MAX_OUTPUT_TOKENS,
temperature: Optional[float] = None,
) -> "TextGenerationResponse":
"""Gets model response for a single prompt.
Args:
prefix: Code before the current point.
suffix: Code after the current point.
max_output_tokens: Max length of the output text in tokens. Range: [1, 1000].
temperature: Controls the randomness of predictions. Range: [0, 1].