零樣本最佳化工具

零樣本最佳化工具可自動修正及改善使用者撰寫的提示。如果提示的語言含糊不清、缺少背景脈絡或包含不相關的資訊,模型通常無法產生您想要的回覆。這項最佳化工具會分析並改寫現有提示,使其更清楚、更有效,且更符合模型功能,最終產生更高品質的回覆。

零樣本最佳化工具特別適合用於:

  • 配合模型更新:升級至新版模型後,現有提示可能無法發揮最佳效果。

  • 提升提示理解能力:如果提示措辭複雜或可能遭到誤解,這項工具可以重新措辭,盡量清楚準確,減少產生不當結果的機率。

最佳化工具的使用方式有兩種:

  • 產生指令:不必從頭編寫複雜的系統指令,只要以簡單的語言說明目標或工作,最佳化工具隨即會產生一組完整且結構良好的系統指令,協助您達成目標。

  • 修正提示:您已建立提示,但模型輸出的內容不一致、稍微離題,或缺乏您想要的詳細資訊。最佳化工具可協助改善提示,生成更優質的內容。

最佳化工具支援 Gemini 支援的所有語言,並可透過 Vertex AI SDK 使用。

事前準備

為確保 Compute Engine 預設服務帳戶具備最佳化提示所需的權限,請要求管理員授予Compute Engine 預設服務帳戶專案的下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

管理員或許也能透過自訂角色或其他預先定義的角色,將必要權限授予 Compute Engine 預設服務帳戶

將提示最佳化

# Import libraries
import vertexai
import logging

# Google Colab authentication
from google.colab import auth
PROJECT_NAME = "PROJECT"
auth.authenticate_user(project_id=PROJECT_NAME)

# Initialize the Vertex AI client
client = vertexai.Client(project=PROJECT_NAME, location='us-central1')

# Input original prompt to optimize
prompt = """You are a professional chef. Your goal is teaching how to cook healthy cooking recipes to your apprentice.

Given a question from your apprentice and some context, provide the correct answer to the question.
Use the context to return a single and correct answer with some explanation.
"""

# Optimize prompt
output = client.prompt_optimizer.optimize_prompt(prompt=prompt)

# View optimized prompt
print(output.model_dump_json(indent=2))

這個 output 物件的類型為 OptimizeResponse,可提供最佳化程序相關資訊。最重要的部分是 suggested_prompt,其中包含最佳化提示,可協助您從模型取得更優質的結果。其他欄位 (尤其是 applicable_guidelines) 有助於瞭解系統改善提示的原因和方式,方便您日後撰寫更優質的提示。以下是輸出內容範例:

{
  "optimization_mode": "zero_shot",
  "applicable_guidelines": [
    {
      "applicable_guideline": "Structure",
      "suggested_improvement": "Add role definition.",
      "text_before_change": "...",
      "text_after_change": "Role: You are an AI assistant...\n\nTask Context:\n..."
    },
    {
      "applicable_guideline": "RedundancyInstructions",
      "suggested_improvement": "Remove redundant explanation.",
      "text_before_change": "...",
      "text_after_change": ""
    }
  ],
  "original_prompt": "...",
  "suggested_prompt": "Role: You are an AI assistant...\n\nTask Context:\n..."
}

針對小型模型進行最佳化

Gemma 3n E4B 等較小型的模型,在遵循指令方面的能力與較大型的模型不同。大型模型適用的提示不一定適合這些小型模型。零樣本最佳化工具提供 gemini_nano 模式來解決這個問題。gemini_nano 模式會根據小型模型的特性調整提示,生成更符合小型模型能力範圍的提示。

以下範例說明如何針對較小的模型最佳化提示:

client = vertexai.Client(project=PROJECT_NAME, location='us-central1')
prompt = 'Generate system instructions for analyzing medical articles'

gemini_nano_config = vertexai.types.OptimizerConfig(
    optimization_target=vertexai.types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO
)

response = client.prompt_optimizer.optimize_prompt(
    prompt=prompt,
    config=gemini_nano_config
)

# Or more simpler way to call the prompt optimizer
# response = client.prompt_optimizer.optimize_prompt(
#    prompt=prompt,
#    config={optimization_target=vertexai.types.OptimizeTarget.OPTIMIZATION_TARGET_GEMINI_NANO}
# )