建立參數化提示範本

這個程式碼範例說明如何建構參數化提示範本,以產生多組變數的內容。

程式碼範例

Python

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

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

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

後續步驟

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