Create a parameterized prompt template

This code sample shows how to build a parameterized prompt template to generate content with multiple variable sets.

Code sample

Python

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Python API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import vertexai
from vertexai.preview.prompts import Prompt

# Initialize vertexai
vertexai.init(project=PROJECT_ID, location="us-central1")

variables = [
    {"animal": "Eagles", "activity": "eat berries"},
    {"animal": "Coyotes", "activity": "jump"},
    {"animal": "Squirrels", "activity": "fly"}
]

# define prompt template
prompt = Prompt(
    prompt_data="Do {animal} {activity}?",
    model_name="gemini-1.5-flash-002",
    variables=variables,
    system_instruction="You are a helpful zoologist"
    # generation_config=generation_config, # Optional
    # safety_settings=safety_settings, # Optional
)

# Generates content using the assembled prompt.
responses = []
for variable_set in prompt.variables:
    response = prompt.generate_content(
        contents=prompt.assemble_contents(**variable_set)
    )
    responses.append(response)

for response in responses:
    print(response.text, end="")

# Example response
    # Assembled prompt replacing: 1 instances of variable animal, 1 instances of variable activity
    # Eagles are primarily carnivorous.  While they might *accidentally* ingest a berry......

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.