### setup.py with PyPI Dependencies Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training/create-python-pre-built-container This `setup.py` example demonstrates how to specify standard Python dependencies from PyPI. The `install_requires` argument lists packages like `some_PyPI_package` that will be installed by pip during the training application setup. ```python from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['some_PyPI_package>=1.0'] setup( name='trainer', version='0.1', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, description='My training application.' ) ``` -------------------------------- ### Python Quickstart: Generate Content with Agent Platform Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/sdks/overview A quickstart example for generating content using the Gemini API on Agent Platform. This example uses the 'v1' API version and the 'gemini-2.5-flash' model. ```python from google import genai from google.genai.types import HttpOptions client = genai.Client(http_options=HttpOptions(api_version="v1")) response = client.models.generate_content( model="gemini-2.5-flash", contents="How does AI work?", ) print(response.text) # Example response: # Okay, let's break down how AI works. It's a broad field, so I'll focus on the ... # # Here's a simplified overview: # ... ``` -------------------------------- ### Example: Install pip packages from requirements.txt and add kernel Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/instances/add-environment This example shows how to create a conda environment, activate it, install packages from a requirements.txt file, install ipykernel, and then register the environment as a Jupyter kernel. ```bash conda create -n myenv conda activate myenv conda install pip pip install -r requirements.txt pip install ipykernel DL_ANACONDA_ENV_HOME="${DL_ANACONDA_HOME}/envs/myenv" python -m ipykernel install --prefix "${DL_ANACONDA_ENV_HOME}" --name myenv --display-name myenv ``` -------------------------------- ### Install Go Client Library Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/libraries Install the Google Cloud Notebooks client library for Go using the go get command. ```go go get cloud.google.com/go/notebooks ``` -------------------------------- ### Install Agent Platform SDK for Example Store Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/optimize/example-store/create-examplestore Install the Agent Platform SDK for Example Store using pip. Ensure you have version 1.87.0 or higher. ```bash pip install --upgrade google-cloud-aiplatform>=1.87.0 ``` -------------------------------- ### Install Agents CLI Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/agents/quickstart-adk Run the Agents CLI setup command using uvx. This is the only command you execute directly. ```bash uvx google-agents-cli setup ``` -------------------------------- ### aiplatform.exampleStores Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/access-control Operations for managing example stores, including create, delete, get, list, readExample, update, and writeExample. ```APIDOC ## aiplatform.exampleStores ### Description Provides methods to manage example stores. ### Methods - `create`: Creates an example store. - `delete`: Deletes an example store. - `get`: Retrieves an example store. - `list`: Lists example stores. - `readExample`: Reads an example from the store. - `update`: Updates an example store. - `writeExample`: Writes an example to the store. ``` -------------------------------- ### Setup Script for Application Default Credentials Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/gcp-auth Installs and runs a script to set up application default credentials. This command is an alternative method for setting up ADC. ```bash curl -sSL https://storage.googleapis.com/cloud-samples-data/adc/setup_adc.sh ``` -------------------------------- ### Fetch All Examples with SDK Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/optimize/example-store/retrieve-examples Retrieves all examples from the Example Store, paginated up to 100 per page. Instantiate an ExampleStore object first. ```python from vertexai.preview import example_stores example_store = example_stores.ExampleStore(EXAMPLE_STORE_NAME) # Returns the dictionary representation of FetchExamplesResponse. examples = example_store.fetch_examples() ``` -------------------------------- ### PowerShell Example Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings This example shows how to get multimodal embeddings using PowerShell. It assumes you have the `gcloud` CLI installed and authenticated. ```APIDOC ## POST /v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict ### Description Generates multimodal embeddings for the provided input. ### Method POST ### Endpoint https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict ### Parameters #### Request Body - **text** (string) - Optional - The text to generate embeddings for. - **image** (object) - Optional - The image to generate embeddings for. - **video** (object) - Optional - The video to generate embeddings for. ### Request Example ```json { "instances": [ { "mimeType": "image/jpeg", "content": "BASE64_ENCODED_IMAGE_DATA" } ] } ``` ### Response #### Success Response (200) - **predictions** (array) - An array of prediction objects. - **textEmbedding** (array) - The text embedding vector. - **videoEmbeddings** (array) - An array of video embedding objects, each containing `startOffsetSec`, `endOffsetSec`, and `embedding`. - **imageEmbedding** (array) - The image embedding vector. - **deployedModelId** (string) - The ID of the deployed model. ``` -------------------------------- ### Set Up Virtual Environment and Install Dependencies Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/streamlit/setup-environment Create a Python virtual environment, activate it, and install all required dependencies from the requirements.txt file. ```bash python3 -m venv gemini-streamlit source gemini-streamlit/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Go Quickstart: Generate Text Content Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/sdks/overview Example demonstrating how to generate text content using the Google Gen AI SDK for Go with a text prompt. It includes error handling and prints the response. ```go import ( "context" "fmt" "io" "google.golang.org/genai" ) // generateWithText shows how to generate text using a text prompt. func generateWithText(w io.Writer) error { ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, }) if err != nil { return fmt.Errorf("failed to create genai client: %w", err) } resp, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash", genai.Text("How does AI work?"), nil, ) if err != nil { return fmt.Errorf("failed to generate content: %w", err) } respText := resp.Text() fmt.Fprintln(w, respText) // Example response: // That's a great question! Understanding how AI works can feel like ... // ... // **1. The Foundation: Data and Algorithms** // ... return nil } ``` -------------------------------- ### Get Model Evaluation Slice in Python Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/image-data/classification/evaluate-model This Python snippet demonstrates how to retrieve a model evaluation slice using the Vertex AI SDK. Ensure the SDK is installed and follow the setup instructions for authentication. ```python from google.cloud import aiplatform def get_model_evaluation_slice_sample( project: str, model_id: str, evaluation_id: str, slice_id: str, location: str = "us-central1", api_endpoint: str = "us-central1-aiplatform.googleapis.com", ): """ To obtain evaluation_id run the following commands where LOCATION is the region where the model is stored, PROJECT is the project ID, and MODEL_ID is the ID of your model. model_client = aiplatform.gapic.ModelServiceClient( client_options={ 'api_endpoint':'LOCATION-aiplatform.googleapis.com' } ) evaluations = model_client.list_model_evaluations(parent='projects/PROJECT/locations/LOCATION/models/MODEL_ID') print("evaluations:", evaluations) """ # The AI Platform services require regional API endpoints. client_options = {"api_endpoint": api_endpoint} # Initialize client that will be used to create and send requests. # This client only needs to be created once, and can be reused for multiple requests. client = aiplatform.gapic.ModelServiceClient(client_options=client_options) name = client.model_evaluation_slice_path( project=project, location=location, model=model_id, evaluation=evaluation_id, slice=slice_id, ) response = client.get_model_evaluation_slice(name=name) print("response:", response) ``` -------------------------------- ### Search for Relevant Examples and Generate Content Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/optimize/example-store/quickstart This snippet demonstrates how to search for relevant examples from an example store based on a query and then use these examples to construct a prompt for the Gemini model. It shows the integration of the `ExampleStorePrompt` with the model's generation configuration. ```python query = "what's the fastest way to get to disney from lax" # Search for relevant examples. examples = example_store.search_examples( {"stored_contents_example_key": query}, top_k=3) prompt = ExampleStorePrompt().get_prompt(examples.get("results", [])) model_response = client.models.generate_content( model="gemini-2.0-flash", contents="How do I get to LAX?", config=genai_types.GenerateContentConfig( system_instruction=prompt, tools=[ genai_types.Tool(function_declarations=[get_current_weather_func])] ) ) ``` -------------------------------- ### Upload a Model to Vertex AI Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/model-registry/import-model Use this Java code to upload a custom model to Vertex AI Model Registry. Ensure you have completed the Java setup and authentication as per the quickstart guide. Replace placeholder variables with your project details. ```Java import com.google.api.gax.longrunning.OperationFuture; import com.google.cloud.aiplatform.v1.LocationName; import com.google.cloud.aiplatform.v1.Model; import com.google.cloud.aiplatform.v1.ModelContainerSpec; import com.google.cloud.aiplatform.v1.ModelServiceClient; import com.google.cloud.aiplatform.v1.ModelServiceSettings; import com.google.cloud.aiplatform.v1.UploadModelOperationMetadata; import com.google.cloud.aiplatform.v1.UploadModelResponse; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class UploadModelSample { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException, IOException { // TODO(developer): Replace these variables before running the sample. String project = "YOUR_PROJECT_ID"; String modelDisplayName = "YOUR_MODEL_DISPLAY_NAME"; String metadataSchemaUri = "gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml"; String imageUri = "YOUR_IMAGE_URI"; String artifactUri = "gs://your-gcs-bucket/artifact_path"; uploadModel(project, modelDisplayName, metadataSchemaUri, imageUri, artifactUri); } static void uploadModel( String project, String modelDisplayName, String metadataSchemaUri, String imageUri, String artifactUri) throws IOException, InterruptedException, ExecutionException, TimeoutException { ModelServiceSettings modelServiceSettings = ModelServiceSettings.newBuilder() .setEndpoint("us-central1-aiplatform.googleapis.com:443") .build(); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) { String location = "us-central1"; LocationName locationName = LocationName.of(project, location); ModelContainerSpec modelContainerSpec = ModelContainerSpec.newBuilder().setImageUri(imageUri).build(); Model model = Model.newBuilder() .setDisplayName(modelDisplayName) .setMetadataSchemaUri(metadataSchemaUri) .setArtifactUri(artifactUri) .setContainerSpec(modelContainerSpec) .build(); OperationFuture uploadModelResponseFuture = modelServiceClient.uploadModelAsync(locationName, model); System.out.format( "Operation name: %s\n", uploadModelResponseFuture.getInitialFuture().get().getName()); System.out.println("Waiting for operation to finish..."); UploadModelResponse uploadModelResponse = uploadModelResponseFuture.get(5, TimeUnit.MINUTES); System.out.println("Upload Model Response"); System.out.format("Model: %s\n", uploadModelResponse.getModel()); } } } ``` -------------------------------- ### Run Setup Script Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/pipelines/continuous-training-tutorial Executes the setup.py script to create a source distribution for the training package. ```bash ! cd training_package && python setup.py sdist --formats=gztar && cd .. ``` -------------------------------- ### projects.locations.exampleStores.upsertExamples Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.exampleStores/upsertExamples Create or update Examples in the Example Store. Stay organized with collections. Save and categorize content based on your preferences. ```APIDOC ## Method: exampleStores.upsertExamples ### Description Create or update Examples in the Example Store. Stay organized with collections. Save and categorize content based on your preferences. ### Method POST ### Endpoint `https://{service-endpoint}/v1beta1/{exampleStore}:upsertExamples` ### Parameters #### Path Parameters - **exampleStore** (string) - Required. The name of the ExampleStore resource that examples are added to or updated in. Format: `projects/{project}/locations/{location}/exampleStores/{exampleStore}` #### Request Body - **examples[]** (object (`Example`)) - Required. A list of examples to be created/updated. - **overwrite** (boolean) - Optional. A flag indicating whether an example can be overwritten if it already exists. If False (default) and the example already exists, the example will not be updated. This does not affect behavior if the example does not exist already. ### Response #### Success Response (200) - **results[]** (object (`UpsertResult`)) - A list of results for creating/updating. It's either a successfully created/updated example or a status with an error message. ### Response Example ```json { "results": [ { "example": { // object (Example) }, "status": { // object (Status) } } ] } ``` ``` -------------------------------- ### Example: Install R Essentials in a conda environment Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/instances/add-environment This example demonstrates how to create a conda environment named 'r', activate it, and install the R Essentials package. ```bash conda create -n r conda activate r conda install -c r r-essentials ``` -------------------------------- ### Install NeMo-Run Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training/training-clusters/run-prebuilt-workloads Install the NeMo-Run package from its GitHub repository. This is a one-time setup step. ```python pip install git+https://github.com/NVIDIA/NeMo-Run.git ``` -------------------------------- ### StartInstance Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/rpc/google.cloud.notebooks.v1 Starts a notebook instance. This operation requires the `notebooks.instances.start` IAM permission. ```APIDOC ## StartInstance ### Description Starts a notebook instance. ### Method (Not specified, typically POST) ### Endpoint (Not specified, but likely related to instance resource path) ### Parameters #### Path Parameters - **name** (string) - Required. Format: `projects/{project_id}/locations/{location}/instances/{instance_id}` ``` -------------------------------- ### Install Go Gemini Library Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/libraries Install the new google.golang.org/genai Go library using go get. ```bash go get google.golang.org/genai ``` -------------------------------- ### Install gRPC client on VM instance Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/vertex-psc-vector-search Installs git, clones the gRPC repository, installs build dependencies, and compiles the grpc_cli tool within the 'on-prem-client' VM instance. This process can take approximately 30 minutes. ```bash sudo apt-get install git -y git clone https://github.com/grpc/grpc.git sudo apt-get install build-essential autoconf libtool pkg-config -y sudo apt-get install cmake -y cd grpc/ git submodule update --init mkdir -p cmake/build cd cmake/build cmake -DgRPC_BUILD_TESTS=ON ../.. make grpc_cli ``` -------------------------------- ### Python Quickstart: Generate Content with Agent Platform (Express Mode) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/sdks/overview Quickstart for generating content using Agent Platform in express mode. Requires an API key and sets `vertexai=True` for the client. ```python from google import genai # TODO(developer): Update below line API_KEY = "YOUR_API_KEY" client = genai.Client(vertexai=True, api_key=API_KEY) response = client.models.generate_content( model="gemini-2.5-flash", contents="Explain bubble sort to me.", ) print(response.text) # Example response: # Bubble Sort is a simple sorting algorithm that repeatedly steps through the list ``` -------------------------------- ### Python Example Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings This example demonstrates how to get multimodal embeddings using the Vertex AI SDK for Python. ```APIDOC ## MultiModalEmbeddingModel.get_embeddings ### Description Generates multimodal embeddings for the provided image, video, and text. ### Method `get_embeddings` ### Parameters - **image** (Image) - Optional - The image object to generate embeddings for. - **video** (Video) - Optional - The video object to generate embeddings for. - **video_segment_config** (VideoSegmentConfig) - Optional - Configuration for video segmentation. - **start_offset_sec** (float) - The start time in seconds for the video segment. - **end_offset_sec** (float) - The end time in seconds for the video segment. - **contextual_text** (string) - Optional - Text to provide context for the embeddings. ### Request Example ```python import vertexai from vertexai.vision_models import Image, MultiModalEmbeddingModel, Video, VideoSegmentConfig # TODO(developer): Update & uncomment line below # PROJECT_ID = "your-project-id" vertexai.init(project=PROJECT_ID, location="us-central1") model = MultiModalEmbeddingModel.from_pretrained("multimodalembedding@001") image = Image.load_from_file("gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png") video = Video.load_from_file("gs://cloud-samples-data/vertex-ai-vision/highway_vehicles.mp4") embeddings = model.get_embeddings( image=image, video=video, video_segment_config=VideoSegmentConfig(end_offset_sec=1), contextual_text="Cars on Highway", ) print(f"Image Embedding: {embeddings.image_embedding}") print("Video Embeddings:") for video_embedding in embeddings.video_embeddings: print(f"Video Segment: {video_embedding.start_offset_sec} - {video_embedding.end_offset_sec}") print(f"Embedding: {video_embedding.embedding}") print(f"Text Embedding: {embeddings.text_embedding}") ``` ### Response - **image_embedding** (list) - The embedding vector for the image. - **video_embeddings** (list) - A list of embedding vectors for video segments. - **text_embedding** (list) - The embedding vector for the text. ``` -------------------------------- ### Get Multimodal Embeddings using Vertex AI SDK for Python Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/embeddings/get-multimodal-embeddings Use the Vertex AI SDK for Python to generate multimodal embeddings. This example loads an image from Google Cloud Storage and provides contextual text. Ensure you have installed the Vertex AI SDK and initialized it with your project ID and location. ```python import vertexai from vertexai.vision_models import Image, MultiModalEmbeddingModel # TODO(developer): Update & uncomment line below # PROJECT_ID = "your-project-id" vertexai.init(project=PROJECT_ID, location="us-central1") model = MultiModalEmbeddingModel.from_pretrained("multimodalembedding@001") image = Image.load_from_file( "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png" ) embeddings = model.get_embeddings( image=image, contextual_text="Colosseum", dimension=1408, ) print(f"Image Embedding: {embeddings.image_embedding}") print(f"Text Embedding: {embeddings.text_embedding}") ``` -------------------------------- ### Sample Prompt: Create Compute Engine Instance Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/instances/gemini-cli This prompt demonstrates how to create a Compute Engine instance with a specified image and machine type. ```bash Create a Compute Engine instance with a Debian 11 image and an n1-standard-4 machine type. ``` -------------------------------- ### Basic setup.py for Training Application Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training/create-python-pre-built-container This `setup.py` file is used with Setuptools to create a Python source distribution for a training application. It specifies the package name, version, and includes all subdirectories with an `__init__.py` file as packages. ```python from setuptools import find_packages from setuptools import setup setup( name='trainer', version='0.1', packages=find_packages(), include_package_data=True, description='My training application.' ) ``` -------------------------------- ### Response Example for Get Endpoint Configuration Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/request-response-logging Example JSON response when retrieving endpoint configuration, showing the logging settings. ```json { "loggingConfig": { "enabled": true, "samplingRate": 1, "bigqueryDestination": { "outputUri": "bq://output-uri" }, "enableOtelLogging": true } } ``` -------------------------------- ### projects.locations.instances.start Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/rest/v1/projects.locations.instances/start Starts a notebook instance. Requires the `notebooks.instances.start` IAM permission and the `https://www.googleapis.com/auth/cloud-platform` OAuth scope. ```APIDOC ## POST projects.locations.instances.start ### Description Starts a notebook instance. ### Method POST ### Endpoint `https://notebooks.googleapis.com/v1/{name}:start` ### Parameters #### Path Parameters - **name** (string) - Required. Format: `projects/{projectId}/locations/{location}/instances/{instanceId}`. Authorization requires the `notebooks.instances.start` IAM permission on the specified resource `name`. #### Request Body The request body must be empty. ### Response #### Success Response (200) If successful, the response body contains an instance of `Operation`. ### Authorization scopes - `https://www.googleapis.com/auth/cloud-platform` ``` -------------------------------- ### StartInstance Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/rpc/google.cloud.notebooks.v1 Starts a notebook instance. Requires the cloud-platform OAuth scope. ```APIDOC ## StartInstance ### Description Starts a notebook instance. ### Method RPC ### Endpoint rpc StartInstance(StartInstanceRequest) returns (Operation) ### Authorization Requires the following OAuth scope: `https://www.googleapis.com/auth/cloud-platform` ``` -------------------------------- ### Get a Skill Revision (Node.js) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/skill-registry/create-manage This Node.js example shows how to get a specific skill revision using the Google Cloud client library. It initializes the client and makes a `get` request for the revision. ```javascript import { Client } from '@google-cloud/agentplatform'; const client = new Client({ project: 'PROJECT_ID', location: 'LOCATION', }); const revision = await client.skills.revisions.get({ name: 'projects/PROJECT_ID/locations/LOCATION/skills/SKILL_ID/revisions/REVISION_ID', }); console.log(revision); ``` -------------------------------- ### List ExampleStores Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.exampleStores/list Lists all ExampleStores within a specified project and location. You can filter the results by page size and token for pagination. ```json { "exampleStores": [ { object (ExampleStore) } ], "nextPageToken": string } ``` -------------------------------- ### Install NumPy via Proxy Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/hybrid-connectivity Install packages like NumPy using a specified proxy. This example demonstrates how to configure pip to use a proxy for package installations after KFP is available in the component image. ```python import subprocess subprocess.call(['pip', 'install', '--proxy', 'https://10.10.10.10:443', 'numpy']) ``` -------------------------------- ### Install Google Gen AI SDK for Node.js Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/content-generation-parameters Install the Google Gen AI SDK for Node.js. This is a prerequisite for using the Node.js code examples. ```bash npm install @google/genai ``` -------------------------------- ### Install Google Gen AI SDK for Python Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/content-generation-parameters Install the Google Gen AI SDK for Python. This is a prerequisite for using the Python code examples. ```bash pip install --upgrade google-genai ``` -------------------------------- ### CLUSTER_SPEC Example Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training/distributed-training An example of the CLUSTER_SPEC JSON string format. This variable describes the cluster setup, including replica roles and indices, for distributed training jobs. ```json { "cluster":{ "workerpool0":[ "cmle-training-workerpool0-ab-0:2222" ], "workerpool1":[ "cmle-training-workerpool1-ab-0:2222", "cmle-training-workerpool1-ab-1:2222" ], "workerpool2":[ "cmle-training-workerpool2-ab-0:2222", "cmle-training-workerpool2-ab-1:2222" ], "workerpool3":[ "cmle-training-workerpool3-ab-0:2222", "cmle-training-workerpool3-ab-1:2222", "cmle-training-workerpool3-ab-2:2222" ] }, "environment":"cloud", "task":{ "type":"workerpool0", "index":0, "trial":"TRIAL_ID" }, "job": { ... } } ``` -------------------------------- ### Install Python Client Library (Windows) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/libraries Set up a Python virtual environment and install the google-cloud-notebooks library using pip on Windows. ```bash pip install --upgrade google-cloud-notebooks pip install virtualenv virtualenv ENVIRONMENT_NAME ENVIRONMENT_NAME\Scripts\activate ENVIRONMENT_NAME\Scripts\pip.exe install google-cloud-notebooks ``` -------------------------------- ### ExampleStoreService Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rpc Manages example stores for AI model demonstrations. ```APIDOC ## ExampleStoreService ### Description Manages example stores for AI model demonstrations. ### Service google.cloud.aiplatform.v1beta1.ExampleStoreService ``` -------------------------------- ### Few-Shot Examples for Classification Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/prompts/introduction-prompt-design Provide examples within the prompt to guide the model in classifying new inputs. This helps dictate the desired output format and accuracy. ```text Classify the following as red wine or white wine: Name: Chardonnay Type: White wine Name: Cabernet Type: Red wine Name: Moscato Type: White wine Name: Riesling Type: ``` -------------------------------- ### Get Predictions with Python SDK Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/predictions/get-online-predictions This Python snippet demonstrates how to get predictions using the Vertex AI SDK. Ensure the SDK is installed and initialized with your project and location. ```python def endpoint_predict_sample( project: str, location: str, instances: list, endpoint: str ): aiplatform.init(project=project, location=location) endpoint = aiplatform.Endpoint(endpoint) prediction = endpoint.predict(instances=instances) print(prediction) return prediction ``` -------------------------------- ### exampleStores.create Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.exampleStores/create Creates an ExampleStore. ExampleStores are used to save and categorize content based on your preferences. ```APIDOC ## POST `https://{service-endpoint}/v1beta1/{parent}/exampleStores` ### Description Creates an ExampleStore. ExampleStores are used to save and categorize content based on your preferences. ### Method POST ### Endpoint `https://{service-endpoint}/v1beta1/{parent}/exampleStores` ### Parameters #### Path Parameters - **parent** (string) - Required - The resource name of the Location to create the ExampleStore in. Format: `projects/{project}/locations/{location}` #### Request Body The request body contains an instance of `ExampleStore`. ### Response #### Success Response (200) If successful, the response body contains a newly created instance of `Operation`. ``` -------------------------------- ### Get Predictions with Node.js Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/predictions/get-online-predictions Use this Node.js snippet to get predictions from a custom-trained model. Ensure you have set up Application Default Credentials and have the necessary client libraries installed. ```javascript /** * TODO(developer): Uncomment these variables before running the sample. * (Not necessary if passing values as arguments) */ // const filename = "YOUR_PREDICTION_FILE_NAME"; // const endpointId = "YOUR_ENDPOINT_ID"; // const project = 'YOUR_PROJECT_ID'; // const location = 'YOUR_PROJECT_LOCATION'; const util = require('util'); const {readFile} = require('fs'); const readFileAsync = util.promisify(readFile); // Imports the Google Cloud Prediction Service Client library const {PredictionServiceClient} = require('@google-cloud/aiplatform'); // Specifies the location of the api endpoint const clientOptions = { apiEndpoint: 'us-central1-aiplatform.googleapis.com', }; // Instantiates a client const predictionServiceClient = new PredictionServiceClient(clientOptions); async function predictCustomTrainedModel() { // Configure the parent resource const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`; const parameters = { structValue: { fields: {}, }, }; const instanceDict = await readFileAsync(filename, 'utf8'); const instanceValue = JSON.parse(instanceDict); const instance = { structValue: { fields: { Age: {stringValue: instanceValue['Age']}, Balance: {stringValue: instanceValue['Balance']}, Campaign: {stringValue: instanceValue['Campaign']}, Contact: {stringValue: instanceValue['Contact']}, Day: {stringValue: instanceValue['Day']}, Default: {stringValue: instanceValue['Default']}, Deposit: {stringValue: instanceValue['Deposit']}, Duration: {stringValue: instanceValue['Duration']}, Housing: {stringValue: instanceValue['Housing']}, Job: {stringValue: instanceValue['Job']}, Loan: {stringValue: instanceValue['Loan']}, MaritalStatus: {stringValue: instanceValue['MaritalStatus']}, Month: {stringValue: instanceValue['Month']}, PDays: {stringValue: instanceValue['PDays']}, POutcome: {stringValue: instanceValue['POutcome']}, Previous: {stringValue: instanceValue['Previous']}, }, }, }; const instances = [instance]; const request = { endpoint, instances, parameters, }; // Predict request const [response] = await predictionServiceClient.predict(request); console.log('Predict custom trained model response'); console.log(` Deployed model id : ${response.deployedModelId}`); const predictions = response.predictions; console.log(' Predictions :'); for (const prediction of predictions) { console.log(` Prediction : ${JSON.stringify(prediction)}`); } } predictCustomTrainedModel(); ``` -------------------------------- ### Example Dockerfile for Serverless Training Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/training/create-custom-container This Dockerfile provides a generic structure for serverless training. It includes instructions for setting a base image, working directory, installing dependencies, copying training code, and configuring the entrypoint. ```dockerfile # Specifies base image and tag FROM image:tag WORKDIR /root # Installs additional packages RUN pip install pkg1 pkg2 pkg3 # Downloads training data RUN curl https://example-url/path-to-data/data-filename --output /root/data-filename # Copies the trainer code to the docker image. COPY your-path-to/model.py /root/model.py COPY your-path-to/task.py /root/task.py # Sets up the entrypoint to invoke the trainer. ENTRYPOINT ["python", "task.py"] ``` -------------------------------- ### API Explorer - Start Runtime Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/rest/v1/projects.locations.runtimes/start This is an example of how to use the API Explorer to start a managed notebook runtime. It shows the structure for setting request parameters and the request body. ```JSON { // Add request body parameters } ``` -------------------------------- ### projects.locations.exampleStores.fetchExamples Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.exampleStores/fetchExamples Fetches examples from a specified Example Store. You can filter by example IDs or metadata, and control the number of results per page. ```APIDOC ## Method: exampleStores.fetchExamples ### Description Get Examples from the Example Store. This method allows fetching examples with optional filtering by IDs or metadata, and supports pagination. ### Method POST ### Endpoint `https://{service-endpoint}/v1beta1/{exampleStore}:fetchExamples` ### Path parameters * **exampleStore** (string) - Required. The name of the ExampleStore resource that the examples should be fetched from. Format: `projects/{project}/locations/{location}/exampleStores/{exampleStore}` ### Request Body * **pageSize** (integer) - Optional. The maximum number of examples to return. If unspecified, at most 100 examples will be returned. * **pageToken** (string) - Optional. The `nextPageToken` value returned from a previous list [ExampleStoreService.FetchExamplesResponse][] call. * **exampleIds[]** (string) - Optional. Example IDs to fetch. If both metadata filters and Example IDs are specified, then both id and metadata filtering will be applied. * **metadata_filter** (Union type) - Optional. The example type-specific filters to be applied to the fetch operation. Can be one of the following: * **storedContentsExampleFilter** (object (`StoredContentsExampleFilter`)) - The metadata filters for StoredContentsExamples. ### Response Body #### Success Response (200) * **examples[]** (object (`Example`)) - The examples in the Example Store that satisfy the metadata filters. * **nextPageToken** (string) - A token, which can be sent as `FetchExamplesRequest.page_token` to retrieve the next page. Absence of this field indicates there are no subsequent pages. ### Response Example ```json { "examples": [ { "object (Example)" } ], "nextPageToken": "string" } ``` ``` -------------------------------- ### Create Source Distribution Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/vertex-psc-batch-predictions Creates a gztar source distribution of the training application using setup.py. ```bash !cd training_package && python setup.py sdist --formats=gztar ``` -------------------------------- ### Get Operation Status (REST) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/general/long-running-operations Use this GET request to retrieve the status of a long-running operation. Replace OPERATION_NAME with the actual operation name returned when the operation was started. ```HTTP GET https://LOCATION-aiplatform.googleapis.com/v1/OPERATION_NAME ``` -------------------------------- ### Quickstart: Generate Content with Gemini API and Vertex AI Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/sdks/overview This JavaScript snippet shows how to initialize the Google Gen AI SDK and generate content. It includes examples for both direct API access using an API key and for using Vertex AI with project and location details. Ensure environment variables like GEMINI_API_KEY, GOOGLE_CLOUD_PROJECT, and GOOGLE_CLOUD_LOCATION are set. ```javascript /** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION; const GOOGLE_GENAI_USE_VERTEXAI = process.env.GOOGLE_GENAI_USE_VERTEXAI; async function generateContentFromMLDev() { const ai = new GoogleGenAI({vertexai: false, apiKey: GEMINI_API_KEY}); const response = await ai.models.generateContent({ model: 'gemini-2.0-flash', contents: 'why is the sky blue?', }); console.debug(response.text); } async function generateContentFromVertexAI() { const ai = new GoogleGenAI({ vertexai: true, project: GOOGLE_CLOUD_PROJECT, location: GOOGLE_CLOUD_LOCATION, }); const response = await ai.models.generateContent({ model: 'gemini-2.0-flash', contents: 'why is the sky blue?', }); console.debug(response.text); } async function main() { if (GOOGLE_GENAI_USE_VERTEXAI) { await generateContentFromVertexAI().catch((e) => console.error('got error', e), ); } else { await generateContentFromMLDev().catch((e) => console.error('got error', e), ); } } main(); ``` -------------------------------- ### Multishot Prompting Example Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking This prompt demonstrates multishot prompting by providing example input-output pairs to guide the model's response format and content for a new query. ```text Example 1: User: What is the tallest mountain in the world? Assistant: Mount Everest Example 2: User: What is the largest ocean? Assistant: Pacific Ocean User: What is the longest river in the world? Assistant: ``` -------------------------------- ### Get a Skill Revision (Python) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/skill-registry/create-manage Use the Python client library to retrieve a specific skill revision. This example initializes the client and calls the `get` method on the revisions resource. ```python import agentplatform client = agentplatform.Client(project="PROJECT_ID", location="LOCATION") revision = client.skills.revisions.get( name="projects/PROJECT_ID/locations/LOCATION/skills/SKILL_ID/revisions/REVISION_ID" ) print(revision) ``` -------------------------------- ### Install Python Client Library (Mac/Linux) Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/notebooks/workbench/reference/libraries Set up a Python virtual environment and install the google-cloud-notebooks library using pip. ```bash pip install virtualenv virtualenv ENVIRONMENT_NAME source ENVIRONMENT_NAME/bin/activate ENVIRONMENT_NAME/bin/pip install google-cloud-notebooks ```