Source code for langchain_community.utilities.vertexai
"""Utilities to init Vertex AI."""fromimportlibimportmetadatafromtypingimportTYPE_CHECKING,Any,Callable,Optional,Unionfromlangchain_core.callbacksimport(AsyncCallbackManagerForLLMRun,CallbackManagerForLLMRun,)fromlangchain_core.language_models.llmsimportBaseLLM,create_base_retry_decoratorifTYPE_CHECKING:fromgoogle.api_core.gapic_v1.client_infoimportClientInfofromgoogle.auth.credentialsimportCredentialsfromvertexai.preview.generative_modelsimportImage
[docs]defcreate_retry_decorator(llm:BaseLLM,*,max_retries:int=1,run_manager:Optional[Union[AsyncCallbackManagerForLLMRun,CallbackManagerForLLMRun]]=None,)->Callable[[Any],Any]:"""Create a retry decorator for Vertex / Palm LLMs."""importgoogle.api_coreerrors=[google.api_core.exceptions.ResourceExhausted,google.api_core.exceptions.ServiceUnavailable,google.api_core.exceptions.Aborted,google.api_core.exceptions.DeadlineExceeded,google.api_core.exceptions.GoogleAPIError,]decorator=create_base_retry_decorator(error_types=errors,max_retries=max_retries,run_manager=run_manager)returndecorator
[docs]defraise_vertex_import_error(minimum_expected_version:str="1.38.0")->None:"""Raise ImportError related to Vertex SDK being not available. Args: minimum_expected_version: The lowest expected version of the SDK. Raises: ImportError: an ImportError that mentions a required version of the SDK. """raiseImportError("Please, install or upgrade the google-cloud-aiplatform library: "f"pip install google-cloud-aiplatform>={minimum_expected_version}")
[docs]definit_vertexai(project:Optional[str]=None,location:Optional[str]=None,credentials:Optional["Credentials"]=None,)->None:"""Init Vertex AI. Args: project: The default GCP project to use when making Vertex API calls. location: The default location to use when making API calls. credentials: The default custom credentials to use when making API calls. If not provided credentials will be ascertained from the environment. Raises: ImportError: If importing vertexai SDK did not succeed. """try:importvertexaiexceptImportError:raise_vertex_import_error()vertexai.init(project=project,location=location,credentials=credentials,)
[docs]defget_client_info(module:Optional[str]=None)->"ClientInfo":r"""Return a custom user agent header. Args: module (Optional[str]): Optional. The module for a custom user agent header. Returns: google.api_core.gapic_v1.client_info.ClientInfo """try:fromgoogle.api_core.gapic_v1.client_infoimportClientInfoexceptImportErrorasexc:raiseImportError("Could not import ClientInfo. Please, install it with ""pip install google-api-core")fromexclangchain_version=metadata.version("langchain")client_library_version=(f"{langchain_version}-{module}"ifmoduleelselangchain_version)returnClientInfo(client_library_version=client_library_version,user_agent=f"langchain/{client_library_version}",)
[docs]defload_image_from_gcs(path:str,project:Optional[str]=None)->"Image":"""Load an image from Google Cloud Storage."""try:fromgoogle.cloudimportstorageexceptImportError:raiseImportError("Could not import google-cloud-storage python package.")fromvertexai.preview.generative_modelsimportImagegcs_client=storage.Client(project=project)pieces=path.split("/")blobs=list(gcs_client.list_blobs(pieces[2],prefix="/".join(pieces[3:])))iflen(blobs)>1:raiseValueError(f"Found more than one candidate for {path}!")returnImage.from_bytes(blobs[0].download_as_bytes())