微調教學課程

本教學課程將說明如何使用 Python SDK 或 REST API (使用 curl) 開始使用 Gemini API 調整服務。這些範例說明如何調整 Gemini API 文字生成服務背後的文字模型。

在 ai.google.dev 上查看 試用 Colab 筆記本 在 GitHub 中查看筆記本

限制

調整模型前,請注意下列限制:

微調資料集

針對 Gemini 1.5 Flash 微調資料集時,請注意下列限制:

  • 每個範例的輸入大小上限為 40,000 個半形字元。
  • 每個範例的輸出大小上限為 5,000 個字元。
  • 系統僅支援輸入/輸出組合的範例。不支援即時通訊風格的多回合對話。

調整後的模型

經過調整的模型有下列限制:

  • 經過調整的 Gemini 1.5 Flash 模型輸入限制為 40,000 個半形字元。
  • 經過調整的模型不支援 JSON 模式。
  • 僅支援文字輸入。

事前準備:設定專案和 API 金鑰

在呼叫 Gemini API 之前,您需要設定專案並設定 API 金鑰。

列出調整後的模型

您可以使用 tunedModels.list 方法查看現有的調校模型。

from google import genai
client = genai.Client() # Get the key from the GOOGLE_API_KEY env variable

for model_info in client.models.list():
    print(model_info.name)

建立調整後模型

如要建立經過調整的模型,您必須在 tunedModels.create 方法中將資料集傳遞至模型。

在這個範例中,您將調整模型,以便產生序列中的下一個數字。舉例來說,如果輸入內容是 1,模型應輸出 2。如果輸入值為 one hundred,輸出值應為 one hundred one

# create tuning model
training_dataset =  [
    ["1", "2"],
    ["3", "4"],
    ["-3", "-2"],
    ["twenty two", "twenty three"],
    ["two hundred", "two hundred one"],
    ["ninety nine", "one hundred"],
    ["8", "9"],
    ["-98", "-97"],
    ["1,000", "1,001"],
    ["10,100,000", "10,100,001"],
    ["thirteen", "fourteen"],
    ["eighty", "eighty one"],
    ["one", "two"],
    ["three", "four"],
    ["seven", "eight"],
]
training_dataset=types.TuningDataset(
        examples=[
            types.TuningExample(
                text_input=i,
                output=o,
            )
            for i,o in training_dataset
        ],
    )
tuning_job = client.tunings.tune(
    base_model='models/gemini-1.0-pro-001',
    training_dataset=training_dataset,
    config=types.CreateTuningJobConfig(
        epoch_count= 5,
        batch_size=4,
        learning_rate=0.001,
        tuned_model_display_name="test tuned model"
    )
)

# generate content with the tuned model
response = client.models.generate_content(
    model=tuning_job.tuned_model.model,
    contents='III',
)

print(response.text)

迭代次數、批次大小和學習率的最佳值取決於資料集和用途的其他限制。如要進一步瞭解這些值,請參閱「進階調整設定」和「超參數」。

試用模型

您可以使用 tunedModels.generateContent 方法,並指定經過調整的模型名稱來測試其效能。

response = client.models.generate_content(
    model=tuning_job.tuned_model.model,
    contents='III'
)

未實作

部分功能 (進度回報、更新說明和刪除調校模型) 尚未在新的 SDK 中實作。