API REST: Điều chỉnh mô hình

Xem trên ai.google.dev Chạy trong Google Colab Xem nguồn trên GitHub

Trong sổ tay này, bạn sẽ tìm hiểu cách bắt đầu sử dụng dịch vụ điều chỉnh API Gemini bằng lệnh curl hoặc API yêu cầu Python để gọi API Gemini. Tại đây, bạn sẽ tìm hiểu cách điều chỉnh mô hình văn bản dùng để hỗ trợ dịch vụ tạo văn bản của API Gemini.

Thiết lập

Xác thực

API Gemini cho phép bạn điều chỉnh mô hình trên dữ liệu của riêng mình. Vì đó là dữ liệu của bạn và các mô hình đã được điều chỉnh, nên cần kiểm soát quyền truy cập nghiêm ngặt hơn so với các Khoá API có thể cung cấp.

Để có thể chạy hướng dẫn này, bạn cần thiết lập OAuth cho dự án.

Trong Colab, cách thiết lập dễ dàng nhất là sao chép nội dung của tệp client_secret.json vào "Trình quản lý bí mật" của Colab (bên dưới biểu tượng khoá trong bảng điều khiển bên trái) dưới tên bí mật CLIENT_SECRET.

Lệnh gcloud này biến tệp client_secret.json thành thông tin xác thực có thể dùng để xác thực với dịch vụ.

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).

Gọi API REST bằng CURL

Phần này đưa ra ví dụ về các câu lệnh curl để gọi API REST. Bạn sẽ tìm hiểu cách tạo công việc điều chỉnh, kiểm tra trạng thái của nó và sau khi hoàn tất, thực hiện một lệnh gọi dự đoán.

Đặt biến

Đặt biến cho các giá trị định kỳ để dùng cho các lệnh gọi API REST còn lại. Mã này đang sử dụng thư viện Python os để đặt các biến môi trường có thể truy cập được trong tất cả các ô mã.

Tính năng này dành riêng cho môi trường sổ tay Colab. Mã trong ô chứa mã tiếp theo tương đương với việc chạy các lệnh sau trong một thiết bị đầu cuối bash.

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"

Liệt kê các mô hình đã được điều chỉnh

Xác minh chế độ xác thực của bạn bằng cách liệt kê các mô hình đã được điều chỉnh hiện có.


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

Tạo mô hình được điều chỉnh

Để tạo một mô hình được điều chỉnh, bạn cần truyền tập dữ liệu vào mô hình trong trường training_data.

Trong ví dụ này, bạn sẽ điều chỉnh một mô hình để tạo ra số tiếp theo trong chuỗi. Ví dụ: nếu đầu vào là 1, mô hình sẽ xuất 2. Nếu dữ liệu đầu vào là one hundred, thì dữ liệu đầu ra phải là one hundred one.


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

Điều chỉnh trạng thái mô hình

Trạng thái của mô hình được đặt thành CREATING trong quá trình huấn luyện và sẽ thay đổi thành ACTIVE sau khi hoàn tất.

Dưới đây là một đoạn mã python để phân tích cú pháp tên mô hình đã tạo qua phản hồi JSON. Nếu đang chạy lệnh này trong một thiết bị đầu cuối, thì bạn có thể thử sử dụng trình phân tích cú pháp bash JSON để phân tích cú pháp phản hồi.

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

Thực hiện một yêu cầu GET khác với tên mô hình để lấy siêu dữ liệu mô hình có bao gồm trường trạng thái.


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

Chạy suy luận

Sau khi công việc điều chỉnh hoàn tất, bạn có thể sử dụng công việc đó để tạo văn bản bằng dịch vụ văn bản. Thử nhập một chữ số La Mã, giả sử 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"
      }
    ]
  }
}

Kết quả đầu ra từ mô hình của bạn có thể chính xác hoặc không. Nếu mô hình được điều chỉnh không hoạt động theo các tiêu chuẩn mà bạn yêu cầu, bạn có thể thử thêm nhiều ví dụ chất lượng cao hơn, hiệu chỉnh siêu tham số hoặc thêm phần mở đầu vào ví dụ của mình. Bạn thậm chí có thể tạo một mô hình được điều chỉnh khác dựa trên mô hình đầu tiên mà bạn đã tạo.

Xem hướng dẫn điều chỉnh để được hướng dẫn thêm về cách cải thiện hiệu suất.

Gọi API REST với các yêu cầu Python

Bạn có thể gọi API còn lại bằng bất kỳ thư viện nào cho phép bạn gửi yêu cầu http. Nhóm ví dụ tiếp theo sử dụng thư viện yêu cầu Python và minh hoạ một số tính năng nâng cao hơn.

Đặt biến

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"

Nhập thư viện requests.

import requests
import json

Liệt kê các mô hình đã được điều chỉnh

Xác minh chế độ xác thực của bạn bằng cách liệt kê các mô hình đã được điều chỉnh hiện có.

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()

Tạo mô hình được điều chỉnh

Tương tự như ví dụ về Curl, bạn truyền tập dữ liệu thông qua trường training_data.

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'} }

Đặt biến có tên của mô hình đã được điều chỉnh để sử dụng cho các lệnh gọi còn lại.

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

Điều chỉnh trạng thái mô hình

Bạn có thể kiểm tra tiến trình điều chỉnh bằng cách kiểm tra trường trạng thái. CREATING có nghĩa là công việc điều chỉnh vẫn đang diễn ra và ACTIVE có nghĩa là các huấn luyện đã hoàn tất và mô hình được điều chỉnh đã sẵn sàng để sử dụng.

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

Đoạn mã dưới đây sẽ kiểm tra trường trạng thái 5 giây một lần cho đến khi trường này không còn ở trạng thái 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'}

Chạy suy luận

Sau khi điều chỉnh xong, bạn có thể sử dụng công việc này để tạo văn bản giống như cách bạn sử dụng mô hình văn bản cơ sở. Thử nhập một chữ số tiếng Nhật, chẳng hạn như 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'}]} }

Kết quả đầu ra từ mô hình của bạn có thể chính xác hoặc không. Nếu mô hình được điều chỉnh không hoạt động theo các tiêu chuẩn mà bạn yêu cầu, bạn có thể thử thêm nhiều ví dụ chất lượng cao hơn, hiệu chỉnh siêu tham số hoặc thêm phần mở đầu vào ví dụ của mình.

Kết luận

Mặc dù dữ liệu huấn luyện không chứa bất kỳ tham chiếu nào đến chữ số La Mã hoặc tiếng Nhật, nhưng mô hình này vẫn có thể khái quát hoá chính xác sau khi tinh chỉnh. Bằng cách này, bạn có thể tinh chỉnh các mô hình để phục vụ cho các trường hợp sử dụng của mình.

Các bước tiếp theo

Để tìm hiểu cách sử dụng dịch vụ điều chỉnh với sự trợ giúp của SDK Python cho API Gemini, hãy truy cập vào phần bắt đầu nhanh điều chỉnh bằng Python. Để tìm hiểu cách sử dụng các dịch vụ khác trong API Gemini, hãy truy cập vào phần hướng dẫn bắt đầu nhanh về Python.