Mengontrol output yang dihasilkan

Anda dapat menjamin bahwa output yang dihasilkan model selalu mengikuti skema tertentu, sehingga Anda menerima respons yang diformat secara konsisten. Misalnya, Anda mungkin memiliki skema data yang telah ditetapkan untuk tugas lain. Jika Anda memiliki model yang mengikuti skema yang sama, Anda dapat langsung mengekstrak data dari output model tanpa pascapemrosesan apa pun.

Untuk menentukan struktur output model, tentukan skema respons yang berfungsi seperti cetak biru untuk respons model. Saat Anda mengirimkan perintah dan menyertakan skema respons, respons model selalu mengikuti skema yang ditentukan.

Anda hanya dapat menggunakan Gemini 1.5 Pro untuk mengontrol output yang dihasilkan.

Contoh kasus penggunaan

Salah satu kasus penggunaan untuk menerapkan skema respons adalah memastikan respons model menghasilkan JSON yang valid dan sesuai dengan skema Anda. Output model generatif dapat memiliki beberapa tingkat variabilitas. Jadi, menyertakan skema respons akan memastikan bahwa Anda selalu menerima JSON yang valid. Dengan demikian, tugas downstream Anda dapat dengan andal mengharapkan input JSON yang valid dari respons yang dihasilkan.

Contoh lain adalah membatasi bagaimana model dapat merespons. Misalnya, Anda dapat meminta model menganotasi teks dengan label buatan pengguna, bukan dengan label yang dihasilkan oleh model. Batasan ini berguna jika Anda mengharapkan kumpulan label tertentu seperti positive atau negative, dan tidak ingin menerima campuran label lain seperti good atau bad.

Pertimbangan

Pertimbangan berikut membahas potensi batasan jika Anda berencana menggunakan skema respons:

  • JSON adalah satu-satunya format output yang didukung.
  • Anda harus menggunakan API untuk menentukan dan menggunakan skema respons. Tidak ada dukungan konsol.
  • Skema respons dihitung terhadap batas token input.

Sebelum memulai

Tentukan skema respons untuk menentukan struktur output model, nama kolom, dan jenis data yang diharapkan untuk setiap kolom. Vertex AI menggunakan subkumpulan objek skema OpenAPI 3.0. Untuk mengetahui informasi selengkapnya, baca referensi skema Vertex AI.

Untuk mengetahui contohnya, lihat Contoh skema dan respons model.

Perilaku model dan skema respons

Saat menghasilkan respons, model akan menggunakan nama kolom dan konteks dari perintah Anda. Oleh karena itu, sebaiknya gunakan struktur yang jelas dan nama kolom yang tidak ambigu agar intent Anda jelas.

Secara default, kolom bersifat opsional, artinya model dapat mengisi kolom atau melewatkannya. Anda dapat menetapkan kolom sebagaimana diperlukan untuk memaksa model memberikan nilai. Jika konteks tidak mencukupi dalam permintaan input terkait, model akan menghasilkan respons terutama berdasarkan data yang digunakan untuk melatihnya.

Jika Anda tidak melihat hasil yang diharapkan, tambahkan lebih banyak konteks ke perintah input atau revisi skema respons Anda. Misalnya, tinjau respons model tanpa pembuatan terkontrol untuk melihat respons model. Kemudian, Anda dapat memperbarui skema respons yang lebih sesuai dengan output model.

Mengirim perintah dengan skema respons

Secara default, semua kolom bersifat opsional, yang berarti model dapat menghasilkan respons terhadap kolom. Untuk memaksa model agar selalu menghasilkan respons terhadap suatu kolom, tetapkan kolom sesuai kebutuhan.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

response_schema = {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "recipe_name": {
                "type": "string",
            },
        },
        "required": ["recipe_name"],
    },
}

model = GenerativeModel("gemini-1.5-pro-001")

response = model.generate_content(
    "List a few popular cookie recipes",
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • GENERATE_RESPONSE_METHOD: Jenis respons yang Anda inginkan untuk dihasilkan model. Pilih metode yang akan menghasilkan cara yang Anda inginkan untuk menampilkan respons model:
    • streamGenerateContent: Respons di-streaming saat dibuat untuk mengurangi persepsi latensi kepada audiens manusia.
    • generateContent: Respons ditampilkan setelah dibuat sepenuhnya.
  • LOCATION: Region untuk memproses permintaan.
  • PROJECT_ID: Project ID Anda.
  • MODEL_ID: ID model dari model multimodal yang ingin Anda gunakan. Opsinya adalah:
    • gemini-1.5-pro
  • ROLE: Peran dalam percakapan yang terkait dengan konten. Menentukan peran diperlukan bahkan dalam kasus penggunaan satu giliran. Nilai yang dapat diterima meliputi:
    • USER: Menentukan konten yang Anda kirimkan.
  • TEXT: Petunjuk teks yang akan disertakan dalam perintah.
  • RESPONSE_SCHEMA: Skema untuk model yang akan diikuti saat membuat respons. Untuk mengetahui informasi selengkapnya, lihat referensi Skema.

Metode HTTP dan URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD

Isi JSON permintaan:

{
  "contents": {
    "role": "ROLE",
    "parts": {
      "text": "TEXT"
    }
  },
  "generation_config": {
    "responseMimeType": "application/json",
    "responseSchema": RESPONSE_SCHEMA,
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

Anda akan melihat respons JSON yang mirip seperti berikut:

Contoh perintah curl

LOCATION="us-central1"
MODEL_ID="gemini-1.0-pro"
PROJECT_ID="test-project"
GENERATE_RESPONSE_METHOD="generateContent"

cat << EOF > request.json
{
  "contents": {
    "role": "user",
    "parts": {
      "text": "List a few popular cookie recipes."
    }
  },
  "generation_config": {
    "maxOutputTokens": 2048,
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "recipe_name": {
            "type": "string",
          },
        },
        "required": ["recipe_name"],
      },
    }
  }
}
EOF

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:${GENERATE_RESPONSE_METHOD} -d \
-d `@request.json`

Contoh respons model dan skema

Bagian berikut menunjukkan berbagai contoh perintah dan skema respons. Respons model sampel juga disertakan setelah setiap sampel kode.

Meringkas rating ulasan

Contoh berikut menghasilkan array objek, dengan setiap objek memiliki dua properti: rating dan nama rasa es krim.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "ARRAY",
        "items": {
            "type": "OBJECT",
            "properties": {
                "rating": {"type": "INTEGER"},
                "flavor": {"type": "STRING"},
            },
        },
    },
}

prompt = """
    Reviews from our social media:

    - "Absolutely loved it! Best ice cream I've ever had." Rating: 4, Flavor: Strawberry Cheesecake
    - "Quite good, but a bit too sweet for my taste." Rating: 1, Flavor: Mango Tango
"""

model = GenerativeModel("gemini-1.5-pro-001")

response = model.generate_content(
    prompt,
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)

Contoh respons model

candidates {
  content {
    role: "model"
    parts {
      text: "[\n    [\n        {\n            \"rating\": 4\n        },\n        {\n            \"flavor\": \"Strawberry Cheesecake\"\n        },\n        {\n            \"rating\": 1\n        },\n        {\n            \"flavor\": \"Mango Tango\"\n        }\n    ]\n] "
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.1139734759926796
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.10070161521434784
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
    probability_score: 0.13695430755615234
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.12241825461387634
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.11676400154829025
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.05310790613293648
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.10521054267883301
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.08299414813518524
  }
}
usage_metadata {
  prompt_token_count: 61
  candidates_token_count: 66
  total_token_count: 127
}

Memperkirakan cuaca untuk setiap hari dalam seminggu

Contoh berikut menghasilkan objek forecast untuk setiap hari dalam seminggu yang menyertakan array properti seperti tingkat suhu dan kelembapan yang diperkirakan untuk hari itu.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

response_schema = {
    "type": "OBJECT",
    "properties": {
        "forecast": {
            "type": "ARRAY",
            "items": {
                "type": "OBJECT",
                "properties": {
                    "Day": {"type": "STRING"},
                    "Forecast": {"type": "STRING"},
                    "Humidity": {"type": "STRING"},
                    "Temperature": {"type": "INTEGER"},
                    "Wind Speed": {"type": "INTEGER"},
                },
                "required": ["Day", "Temperature", "Forecast"],
            },
        }
    },
}

prompt = """
    The week ahead brings a mix of weather conditions.
    Sunday is expected to be sunny with a temperature of 77°F and a humidity level of 50%. Winds will be light at around 10 km/h.
    Monday will see partly cloudy skies with a slightly cooler temperature of 72°F and humidity increasing to 55%. Winds will pick up slightly to around 15 km/h.
    Tuesday brings rain showers, with temperatures dropping to 64°F and humidity rising to 70%. Expect stronger winds at 20 km/h.
    Wednesday may see thunderstorms, with a temperature of 68°F and high humidity of 75%. Winds will be gusty at 25 km/h.
    Thursday will be cloudy with a temperature of 66°F and moderate humidity at 60%. Winds will ease slightly to 18 km/h.
    Friday returns to partly cloudy conditions, with a temperature of 73°F and lower humidity at 45%. Winds will be light at 12 km/h.
    Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
"""

model = GenerativeModel("gemini-1.5-pro-001")

response = model.generate_content(
    prompt,
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)

Contoh respons model

candidates {
  content {
    role: "model"
    parts {
      text: "{\"forecast\": [{\"Day\": \"Sunday\", \"Forecast\": \"Sunny\", \"Temperature\": 77, \"Humidity\": \n\"50\", \"Wind Speed\": 10}, {\"Day\": \"Monday\", \"Forecast\": \"Partly Cloudy\", \"Temperature\": 72, \"Humidity\": \"55\", \"Wind Speed\": 15}, {\"Day\": \"Tuesday\", \"Forecast\": \"Rain Showers\", \"Temperature\": 64, \"Humidity\": \"70\", \"Wind Speed\": 20}, {\"Day\": \"Wednesday\", \"Forecast\": \"Thunderstorms\", \"Temperature\": 68, \"Humidity\": \"75\", \"Wind Speed\": 25}, {\"Day\": \"Thursday\", \"Forecast\": \"Cloudy\", \"Temperature\": 66, \"Humidity\": \"60\", \"Wind Speed\": 18}, {\"Day\": \"Friday\", \"Forecast\": \"Partly Cloudy\", \"Temperature\": 73, \"Humidity\": \"45\", \"Wind Speed\": 12}, {\"Day\": \"Saturday\", \"Forecast\": \"Sunny\", \"Temperature\": 80, \"Humidity\": \"40\", \"Wind Speed\": 8}]} "
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.1037486344575882
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.09670579433441162
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
    probability_score: 0.18126320838928223
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.10052486509084702
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.15960998833179474
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.09518112242221832
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.1388116478919983
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.10539454221725464
  }
}
usage_metadata {
  prompt_token_count: 280
  candidates_token_count: 249
  total_token_count: 529
}

Mengklasifikasikan produk

Contoh berikut mencakup enum ketika model harus mengklasifikasikan jenis dan kondisi objek dari daftar nilai yang diberikan.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "OBJECT",
        "properties": {
            "to_discard": {"type": "INTEGER"},
            "subcategory": {"type": "STRING"},
            "safe_handling": {"type": "INTEGER"},
            "item_category": {
                "type": "STRING",
                "enum": [
                    "clothing",
                    "winter apparel",
                    "specialized apparel",
                    "furniture",
                    "decor",
                    "tableware",
                    "cookware",
                    "toys",
                ],
            },
            "for_resale": {"type": "INTEGER"},
            "condition": {
                "type": "STRING",
                "enum": [
                    "new in package",
                    "like new",
                    "gently used",
                    "used",
                    "damaged",
                    "soiled",
                ],
            },
        },
    },
}

prompt = """
    Item description:
    The item is a long winter coat that has many tears all around the seams and is falling apart.
    It has large questionable stains on it.
"""

model = GenerativeModel("gemini-1.5-pro-001")

response = model.generate_content(
    prompt,
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)

Contoh respons model

candidates {
  content {
    role: "model"
    parts {
      text: " [{\n    \"item_category\": \"winter apparel\",\n    \"subcategory\": \"coat\",\n    \"to_discard\":  1\n  }] "
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.08945459872484207
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.13753245770931244
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
    probability_score: 0.19208428263664246
    severity: HARM_SEVERITY_LOW
    severity_score: 0.23810701072216034
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.07585817575454712
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.04336579889059067
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.12667709589004517
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.07396338135004044
  }
}
usage_metadata {
  prompt_token_count: 38
  candidates_token_count: 33
  total_token_count: 71
}

Mengidentifikasi objek dalam gambar

Contoh berikut mengidentifikasi objek dari dua gambar yang disimpan di Cloud Storage.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import vertexai

from vertexai.generative_models import GenerationConfig, GenerativeModel, Part

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

response_schema = {
    "type": "ARRAY",
    "items": {
        "type": "ARRAY",
        "items": {
            "type": "OBJECT",
            "properties": {
                "object": {"type": "STRING"},
            },
        },
    },
}

model = GenerativeModel("gemini-1.5-pro-001")

response = model.generate_content(
    [
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/office-desk.jpeg",
            "image/jpeg",
        ),
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/gardening-tools.jpeg",
            "image/jpeg",
        ),
        "Generate a list of objects in the images.",
    ],
    generation_config=GenerationConfig(
        response_mime_type="application/json", response_schema=response_schema
    ),
)

print(response.text)

Contoh respons model

candidates {
  content {
    role: "model"
    parts {
      text: "[\n    [\n        {\n            \"object\": \"globe model\"\n        },\n        {\n            \"object\": \"tablet computer\"\n        },\n        {\n            \"object\": \"shopping cart\"\n        },\n        {\n            \"object\": \"Eiffel Tower model\"\n        },\n        {\n            \"object\": \"airplane model\"\n        },\n        {\n            \"object\": \"coffee cup\"\n        },\n        {\n            \"object\": \"computer keyboard\"\n        },\n        {\n            \"object\": \"computer mouse\"\n        },\n        {\n            \"object\": \"passport\"\n        },\n        {\n            \"object\": \"sunglasses\"\n        },\n        {\n            \"object\": \"US Dollar bills\"\n        },\n        {\n            \"object\": \"notepad\"\n        },\n        {\n            \"object\": \"pen\"\n        }\n    ],\n    [\n        {\n            \"object\": \"watering can\"\n        },\n        {\n            \"object\": \"oregano\"\n        },\n        {\n            \"object\": \"flower pot\"\n        },\n        {\n            \"object\": \"flower pot\"\n        },\n        {\n            \"object\": \"gardening gloves\"\n        },\n        {\n            \"object\": \"hand rake\"\n        },\n        {\n            \"object\": \"hand trowel\"\n        },\n        {\n            \"object\": \"grass\"\n        }\n    ]\n] "
    }
  }
  finish_reason: STOP
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
    probability_score: 0.1872812658548355
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.16357900202274323
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: LOW
    probability_score: 0.37920594215393066
    severity: HARM_SEVERITY_LOW
    severity_score: 0.29320207238197327
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
    probability_score: 0.14175598323345184
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.12074951827526093
  }
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
    probability_score: 0.12241825461387634
    severity: HARM_SEVERITY_NEGLIGIBLE
    severity_score: 0.0955180674791336
  }
}
usage_metadata {
  prompt_token_count: 525
  candidates_token_count: 333
  total_token_count: 858
}