บทแนะนำการปรับแต่ง

ดูใน ai.google.dev เรียกใช้ใน Google Colab ดูแหล่งที่มาใน GitHub

ในสมุดบันทึกนี้ คุณจะได้ดูวิธีเริ่มต้นใช้งานบริการปรับแต่ง Gemini API โดยใช้คำสั่ง CURL หรือ API คำขอ Python เพื่อเรียกใช้ Gemini API คุณจะได้ดูวิธีปรับแต่งโมเดลข้อความเบื้องหลังบริการสร้างข้อความของ Gemini API

ตั้งค่าการตรวจสอบสิทธิ์

Gemini API ช่วยให้คุณปรับแต่งโมเดลจากข้อมูลของคุณเองได้ เนื่องจากเป็นข้อมูลของคุณและโมเดลที่คุณปรับแต่ง จึงต้องใช้การควบคุมการเข้าถึงที่เข้มงวดกว่าคีย์ API

คุณจะต้องตั้งค่า OAuth สำหรับโปรเจ็กต์ก่อน จึงจะเรียกใช้บทแนะนำนี้ได้

วิธีที่ง่ายที่สุดในการตั้งค่าใน Colab คือการคัดลอกเนื้อหาของไฟล์ client_secret.json ลงใน "Secret Manager" ของ Colab (ใต้ไอคอนกุญแจในแผงด้านซ้าย) ด้วยชื่อข้อมูลลับ CLIENT_SECRET

คำสั่ง gcloud นี้จะเปลี่ยนไฟล์ client_secret.json เป็นข้อมูลเข้าสู่ระบบที่ใช้ตรวจสอบสิทธิ์กับบริการได้

try:
  from google.colab import userdata
  import pathlib
  pathlib.Path('client_secret.json').write_text(userdata.get('CLIENT_SECRET'))

  # Use `--no-browser` in colab
  !gcloud auth application-default login --no-browser --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'
except ImportError:
  !gcloud auth application-default login --client-id-file client_secret.json --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning'
You are authorizing client libraries without access to a web browser. Please run the following command on a machine with a web browser and copy its output back here. Make sure the installed gcloud version is 372.0.0 or newer.

gcloud auth application-default login --remote-bootstrap="https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=87071151422-n1a3cb6c7fvkfg4gmhdtmn5ulol2l4be.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgenerative-language.tuning&state=QIyNibWSaTIsozjmvZEkVBo6EcoW0G&access_type=offline&code_challenge=76c1ZiGvKN8cvlYfj3BmbCwE4e7tvrlwaX3REUX25gY&code_challenge_method=S256&token_usage=remote"

Enter the output of the above command: https://localhost:8085/?state=QIyNibWSaTIsozjmvZEkVBo6EcoW0G&code=4/0AeaYSHBKrY911S466QjKQIFODoOPXlO1mWyTYYdrbELIDV6Hw2DKRAyro62BugroSvIWsA&scope=https://www.googleapis.com/auth/cloud-platform%20https://www.googleapis.com/auth/generative-language.tuning

Credentials saved to file: [/content/.config/application_default_credentials.json]

These credentials will be used by any library that requests Application Default Credentials (ADC).

ตั้งค่าตัวแปร

CURL

ตั้งค่าตัวแปรสำหรับค่าที่เกิดซ้ำเพื่อใช้กับการเรียก API ของ REST ที่เหลือ โค้ดใช้ไลบรารี Python os เพื่อตั้งค่าตัวแปรสภาพแวดล้อมซึ่งเข้าถึงได้ในเซลล์โค้ดทั้งหมด

ระบบนี้ใช้เฉพาะกับสภาพแวดล้อมสมุดบันทึก Colab เท่านั้น โค้ดในเซลล์โค้ดถัดไปเทียบเท่ากับการเรียกใช้คำสั่งต่อไปนี้ใน Bash Terminal

export access_token=$(gcloud auth application-default print-access-token)
export project_id=my-project-id
export base_url=https://generativelanguage.googleapis.com
import os

access_token = !gcloud auth application-default print-access-token
access_token = '\n'.join(access_token)

os.environ['access_token'] = access_token
os.environ['project_id'] = "[Enter your project-id here]"
os.environ['base_url'] = "https://generativelanguage.googleapis.com"

Python

access_token = !gcloud auth application-default print-access-token
access_token = '\n'.join(access_token)

project = '[Enter your project-id here]'
base_url = "https://generativelanguage.googleapis.com"

นำเข้าไลบรารี requests

import requests
import json

แสดงรายการโมเดลที่ปรับแต่ง

ยืนยันการตั้งค่าการตรวจสอบสิทธิ์โดยแสดงรายการโมเดลที่ปรับแต่งที่พร้อมใช้งาน

CURL


curl -X GET ${base_url}/v1beta/tunedModels \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}"

Python

headers={
  'Authorization': 'Bearer ' + access_token,
  'Content-Type': 'application/json',
  'x-goog-user-project': project
}

result = requests.get(
  url=f'{base_url}/v1beta/tunedModels',
  headers = headers,
)
result.json()

สร้างโมเดลที่ปรับแต่ง

หากต้องการสร้างโมเดลที่ปรับแต่ง คุณต้องส่งชุดข้อมูลไปยังโมเดลในช่อง training_data

สำหรับตัวอย่างนี้ คุณจะปรับแต่งโมเดลเพื่อสร้างตัวเลขถัดไปในลำดับ ตัวอย่างเช่น หากอินพุตคือ 1 โมเดลควรแสดงผลเป็น 2 หากอินพุตคือ one hundred เอาต์พุตควรเป็น one hundred one

CURL


curl -X POST $base_url/v1beta/tunedModels \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}" \
    -d '
      {
        "display_name": "number generator model",
        "base_model": "models/gemini-1.0-pro-001",
        "tuning_task": {
          "hyperparameters": {
            "batch_size": 2,
            "learning_rate": 0.001,
            "epoch_count":5,
          },
          "training_data": {
            "examples": {
              "examples": [
                {
                    "text_input": "1",
                    "output": "2",
                },{
                    "text_input": "3",
                    "output": "4",
                },{
                    "text_input": "-3",
                    "output": "-2",
                },{
                    "text_input": "twenty two",
                    "output": "twenty three",
                },{
                    "text_input": "two hundred",
                    "output": "two hundred one",
                },{
                    "text_input": "ninety nine",
                    "output": "one hundred",
                },{
                    "text_input": "8",
                    "output": "9",
                },{
                    "text_input": "-98",
                    "output": "-97",
                },{
                    "text_input": "1,000",
                    "output": "1,001",
                },{
                    "text_input": "10,100,000",
                    "output": "10,100,001",
                },{
                    "text_input": "thirteen",
                    "output": "fourteen",
                },{
                    "text_input": "eighty",
                    "output": "eighty one",
                },{
                    "text_input": "one",
                    "output": "two",
                },{
                    "text_input": "three",
                    "output": "four",
                },{
                    "text_input": "seven",
                    "output": "eight",
                }
              ]
            }
          }
        }
      }' | tee tunemodel.json
{
"name": "tunedModels/number-generator-model-dzlmi0gswwqb/operations/bvl8dymw0fhw",
"metadata": {
  "@type": "type.googleapis.com/google.ai.generativelanguage.v1beta.CreateTunedModelMetadata",
  "totalSteps": 38,
  "tunedModel": "tunedModels/number-generator-model-dzlmi0gswwqb"
}
}
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                              Dload  Upload   Total   Spent    Left  Speed
100  2280    0   296  100  1984    611   4098 --:--:-- --:--:-- --:--:--  4720

Python

operation = requests.post(
    url = f'{base_url}/v1beta/tunedModels',
    headers=headers,
    json= {
        "display_name": "number generator",
        "base_model": "models/gemini-1.0-pro-001",
        "tuning_task": {
          "hyperparameters": {
            "batch_size": 4,
            "learning_rate": 0.001,
            "epoch_count":5,
          },
          "training_data": {
            "examples": {
              "examples": [
                {
                    'text_input': '1',
                    'output': '2',
                },{
                    'text_input': '3',
                    'output': '4',
                },{
                    'text_input': '-3',
                    'output': '-2',
                },{
                    'text_input': 'twenty two',
                    'output': 'twenty three',
                },{
                    'text_input': 'two hundred',
                    'output': 'two hundred one',
                },{
                    'text_input': 'ninety nine',
                    'output': 'one hundred',
                },{
                    'text_input': '8',
                    'output': '9',
                },{
                    'text_input': '-98',
                    'output': '-97',
                },{
                    'text_input': '1,000',
                    'output': '1,001',
                },{
                    'text_input': '10,100,000',
                    'output': '10,100,001',
                },{
                    'text_input': 'thirteen',
                    'output': 'fourteen',
                },{
                    'text_input': 'eighty',
                    'output': 'eighty one',
                },{
                    'text_input': 'one',
                    'output': 'two',
                },{
                    'text_input': 'three',
                    'output': 'four',
                },{
                    'text_input': 'seven',
                    'output': 'eight',
                }
              ]
            }
          }
        }
      }
)
operation
<Response [200]>
operation.json()
{'name': 'tunedModels/number-generator-wl1qr34x2py/operations/41vni3zk0a47',
'metadata': {'@type': 'type.googleapis.com/google.ai.generativelanguage.v1beta.CreateTunedModelMetadata',
  'totalSteps': 19,
  'tunedModel': 'tunedModels/number-generator-wl1qr34x2py'} }

ตั้งค่าตัวแปรด้วยชื่อโมเดลที่ปรับแต่งเพื่อใช้กับการเรียกที่เหลือ

name=operation.json()["metadata"]["tunedModel"]
name
'tunedModels/number-generator-wl1qr34x2py'

รับสถานะโมเดลที่ปรับแต่ง

สถานะของโมเดลเป็น CREATING ระหว่างการฝึกและจะเปลี่ยนเป็น ACTIVE เมื่อเสร็จสมบูรณ์

CURL

ด้านล่างนี้คือโค้ด Python สำหรับแยกวิเคราะห์ชื่อโมเดลที่สร้างขึ้นจาก JSON การตอบกลับ หากใช้ในเทอร์มินัล ลองใช้โปรแกรมแยกวิเคราะห์ JSON แบบ Bash เพื่อแยกวิเคราะห์การตอบกลับได้

import json

first_page = json.load(open('tunemodel.json'))
os.environ['modelname'] = first_page['metadata']['tunedModel']

print(os.environ['modelname'])
tunedModels/number-generator-model-dzlmi0gswwqb

ส่งคำขอ GET อีกรายการที่มีชื่อโมเดลเพื่อรับข้อมูลเมตาของโมเดลซึ่งมีช่องสถานะ


curl -X GET ${base_url}/v1beta/${modelname} \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}" | grep state
"state": "ACTIVE",
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                              Dload  Upload   Total   Spent    Left  Speed
100  5921    0  5921    0     0  13164      0 --:--:-- --:--:-- --:--:-- 13157

Python

tuned_model = requests.get(
    url = f'{base_url}/v1beta/{name}',
    headers=headers,
)
tuned_model.json()

โค้ดด้านล่างจะตรวจสอบช่องสถานะทุกๆ 5 วินาทีจนกว่ารหัสจะไม่อยู่ในสถานะ CREATING แล้ว

import time
import pprint

op_json = operation.json()
response = op_json.get('response')
error = op_json.get('error')

while response is None and error is None:
    time.sleep(5)

    operation = requests.get(
        url = f'{base_url}/v1/{op_json["name"]}',
        headers=headers,
    )

    op_json = operation.json()
    response = op_json.get('response')
    error = op_json.get('error')

    percent = op_json['metadata'].get('completedPercent')
    if percent is not None:
      print(f"{percent:.2f}% - {op_json['metadata']['snapshots'][-1]}")
      print()

if error is not None:
    raise Exception(error)
100.00% - {'step': 19, 'epoch': 5, 'meanLoss': 1.402067, 'computeTime': '2024-03-14T15:11:23.766989274Z'}

เรียกใช้การอนุมาน

เมื่องานปรับแต่งเสร็จแล้ว คุณจะใช้งานดังกล่าวเพื่อสร้างข้อความด้วยบริการข้อความได้

CURL

ลองป้อนเลขโรมัน เช่น 63 (LXIII):


curl -X POST $base_url/v1beta/$modelname:generateContent \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}" \
    -d '{
        "contents": [{
        "parts": [{
          "text": "LXIII"
          }]
        }]
        }' 2> /dev/null
{
"candidates": [
  {
    "content": {
      "parts": [
        {
          "text": "LXIV"
        }
      ],
      "role": "model"
    },
    "finishReason": "STOP",
    "index": 0,
    "safetyRatings": [
      {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HARASSMENT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "probability": "NEGLIGIBLE"
      }
    ]
  }
],
"promptFeedback": {
  "safetyRatings": [
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "probability": "NEGLIGIBLE"
    },
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "probability": "NEGLIGIBLE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "probability": "NEGLIGIBLE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "probability": "NEGLIGIBLE"
    }
  ]
}
}

เอาต์พุตจากโมเดลของคุณอาจไม่ถูกต้องหรือไม่ถูกต้อง หากโมเดลที่ปรับแต่งไม่เป็นไปตามมาตรฐานที่จำเป็น คุณอาจลองเพิ่มตัวอย่างที่มีคุณภาพสูงขึ้น ปรับแต่งไฮเปอร์พารามิเตอร์ หรือเพิ่มคำนำในตัวอย่าง คุณยังสามารถสร้างโมเดลที่ปรับแต่งอีกแบบหนึ่งโดยอิงตามรูปแบบแรกที่คุณสร้างได้อีกด้วย

ดูคําแนะนําเพิ่มเติมเกี่ยวกับการปรับปรุงประสิทธิภาพได้ในคู่มือการปรับแต่ง

Python

ลองป้อนตัวเลขภาษาญี่ปุ่น เช่น 6 (ศูนย์แจ้งเตือน):

import time

m = requests.post(
    url = f'{base_url}/v1beta/{name}:generateContent',
    headers=headers,
    json= {
        "contents": [{
            "parts": [{
                "text": "六"
            }]
          }]
    })
import pprint
pprint.pprint(m.json())
{'candidates': [{'content': {'parts': [{'text': '七'}], 'role': 'model'},
                'finishReason': 'STOP',
                'index': 0,
                'safetyRatings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
                                    'probability': 'NEGLIGIBLE'},
                                  {'category': 'HARM_CATEGORY_HATE_SPEECH',
                                    'probability': 'NEGLIGIBLE'},
                                  {'category': 'HARM_CATEGORY_HARASSMENT',
                                    'probability': 'LOW'},
                                  {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
                                    'probability': 'NEGLIGIBLE'}]}],
'promptFeedback': {'safetyRatings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
                                      'probability': 'NEGLIGIBLE'},
                                      {'category': 'HARM_CATEGORY_HATE_SPEECH',
                                      'probability': 'NEGLIGIBLE'},
                                      {'category': 'HARM_CATEGORY_HARASSMENT',
                                      'probability': 'NEGLIGIBLE'},
                                      {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
                                      'probability': 'NEGLIGIBLE'}]} }

เอาต์พุตจากโมเดลของคุณอาจไม่ถูกต้องหรือไม่ถูกต้อง หากโมเดลที่ปรับแต่งไม่เป็นไปตามมาตรฐานที่จำเป็น คุณอาจลองเพิ่มตัวอย่างที่มีคุณภาพสูงขึ้น ปรับแต่งไฮเปอร์พารามิเตอร์ หรือเพิ่มคำนำในตัวอย่าง

บทสรุป

แม้ว่าข้อมูลการฝึกจะไม่ได้อ้างอิงถึงตัวเลขโรมันหรือญี่ปุ่น แต่โมเดลก็สามารถทำให้ข้อมูลทั่วไปได้รับการสรุปได้เป็นอย่างดีหลังจากการปรับแต่ง วิธีนี้จะช่วยให้คุณปรับแต่งโมเดลให้เหมาะกับกรณีการใช้งานได้

ขั้นตอนถัดไป

หากต้องการดูวิธีใช้บริการปรับแต่งโดยใช้ Python SDK สำหรับ Gemini API โปรดไปที่การเริ่มต้นอย่างรวดเร็วด้วย Python หากต้องการดูวิธีใช้บริการอื่นๆ ใน Gemini API โปรดไปที่การเริ่มต้น Python อย่างรวดเร็ว