建立並使用 Vertex AI 提示產生文字

本範例說明如何建立 Prompt 執行個體、使用組裝的提示生成文字,以及儲存 Prompt 版本。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:

程式碼範例

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Python API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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-2.0-flash-001",
    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.....

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器