Create and use a Vertex AI Prompt to generate text

This sample demonstrates how to create a Prompt instance, generate text using the assembled prompt, and save a version of the Prompt.

Explore further

For detailed documentation that includes this code sample, see the following:

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 import prompts
from vertexai.preview.prompts import Prompt

# from vertexai.generative_models import GenerationConfig, SafetySetting # Optional

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

# Create local Prompt
local_prompt = Prompt(
    prompt_name="movie-critic",
    prompt_data="Compare the movies {movie1} and {movie2}.",
    variables=[
        {"movie1": "The Lion King", "movie2": "Frozen"},
        {"movie1": "Inception", "movie2": "Interstellar"},
    ],
    model_name="gemini-1.5-pro-002",
    system_instruction="You are a movie critic. Answer in a short sentence.",
    # generation_config=GenerationConfig, # Optional,
    # safety_settings=SafetySetting, # Optional,
)

# Generate content using the assembled prompt for each variable set.
for i in range(len(local_prompt.variables)):
    response = local_prompt.generate_content(
        contents=local_prompt.assemble_contents(**local_prompt.variables[i])
    )
    print(response)

# Save a version
prompt1 = prompts.create_version(prompt=local_prompt)

print(prompt1)

# Example response
# Assembled prompt replacing: 1 instances of variable movie1, 1 instances of variable movie2
# Assembled prompt replacing: 1 instances of variable movie1, 1 instances of variable movie2
# Created prompt resource with id 12345678910.....

What's next

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