Halaman ini menjelaskan cara melakukan hal berikut:
- Mengonfigurasi project untuk menggunakan Prompt API
- Memberikan input khusus teks dan menerima respons
- Memberikan input gambar dengan input teks terkait dan menerima respons
Untuk mengetahui detail selengkapnya tentang Prompt API, lihat dokumentasi referensi untuk Kotlin (com.google.mlkit.genai.prompt) dan Java (com.google.mlkit.genai.prompt.java, com.google.mlkit.genai.prompt).
Konfigurasikan project
Tambahkan ML Kit Prompt API sebagai dependensi dalam konfigurasi build.gradle Anda:
implementation("com.google.mlkit:genai-prompt:1.0.0-beta2")
Mengimplementasikan model generatif
Untuk mengimplementasikan kode di project Anda, ikuti langkah-langkah berikut:
Buat objek
generativeModel:Kotlin
// Get a GenerativeModel instance val generativeModel = Generation.getClient()Java
// Get a GenerativeModel instance GenerativeModelFutures generativeModelFutures = GenerativeModelFutures .from(Generation.INSTANCE.getClient());Periksa apakah Gemini Nano
AVAILABLE,DOWNLOADABLE, atauUNAVAILABLE. Kemudian, download fitur jika dapat didownload:Kotlin
val status = generativeModel.checkStatus() when (status) { FeatureStatus.UNAVAILABLE -> { // Gemini Nano not supported on this device or device hasn't fetched the latest configuration to support it } FeatureStatus.DOWNLOADABLE -> { // Gemini Nano can be downloaded on this device, but is not currently downloaded generativeModel.download().collect { status -> when (status) { is DownloadStatus.DownloadStarted -> Log.d(TAG, "starting download for Gemini Nano") is DownloadStatus.DownloadProgress -> Log.d(TAG, "Nano ${status.totalBytesDownloaded} bytes downloaded") DownloadStatus.DownloadCompleted -> { Log.d(TAG, "Gemini Nano download complete") modelDownloaded = true } is DownloadStatus.DownloadFailed -> { Log.e(TAG, "Nano download failed ${status.e.message}") } } } } FeatureStatus.DOWNLOADING -> { // Gemini Nano currently being downloaded } FeatureStatus.AVAILABLE -> { // Gemini Nano currently downloaded and available to use on this device } }Java
ListenableFuture<Integer> status = generativeModelFutures.checkStatus(); Futures.addCallback(generativeModelFutures.checkStatus(), new FutureCallback<>() { @Override public void onSuccess(Integer featureStatus) { switch (featureStatus) { case FeatureStatus.AVAILABLE - > { // Gemini Nano currently downloaded and available to use on this device } case FeatureStatus.UNAVAILABLE - > { // Gemini Nano not supported on this device or device hasn't fetched the latest configuration to support it } case FeatureStatus.DOWNLOADING - > { // Gemini Nano currently being downloaded } case FeatureStatus.DOWNLOADABLE - > { generativeModelFutures.download(new DownloadCallback() { @Override public void onDownloadStarted(long l) { Log.d(TAG, "starting download for Gemini Nano"); } @Override public void onDownloadProgress(long l) { Log.d(TAG, "Nano " + l + " bytes downloaded"); } @Override public void onDownloadCompleted() { Log.d(TAG, "Gemini Nano download complete"); } @Override public void onDownloadFailed(@NonNull GenAiException e) { Log.e(TAG, "Nano download failed: " + e.getMessage()); } }); } } } @Override public void onFailure(@NonNull Throwable t) { // Failed to check status } }, ContextCompat.getMainExecutor(context));
Memberikan input khusus teks
Kotlin
val response = generativeModel.generateContent("Write a 3 sentence story about a magical dog.")
Java
GenerateContentResponse response = generativeModelFutures.generateContent(
new GenerateContentRequest.Builder(
new TextPart("Write a 3 sentence story about a magical dog."))
.build())
.get();
Atau, tambahkan parameter opsional:
Kotlin
val response = generativeModel.generateContent(
generateContentRequest(
TextPart("Write a 3 sentence story about a magical dog."),
) {
// Optional parameters
temperature = 0.2f
topK = 10
candidateCount = 3
},
)
Java
GenerateContentRequest.Builder requestBuilder =
new GenerateContentRequest.Builder(
new TextPart("Write a 3 sentence story about a magical dog."));
requestBuilder.setTemperature(.2f);
requestBuilder.setTopK(10);
requestBuilder.setCandidateCount(3);
GenerateContentResponse response =
generativeModelFutures.generateContent(requestBuilder.build()).get();
Untuk mengetahui informasi selengkapnya tentang parameter opsional, lihat Konfigurasi opsional.
Memberikan input multimodal (gambar dan teks)
Gabungkan input gambar dan teks dalam fungsi generateContentRequest(), dengan perintah teks berupa pertanyaan atau perintah yang terkait dengan gambar:
Kotlin
val response = generativeModel.generateContent(
generateContentRequest(ImagePart(bitmap), TextPart(textPrompt)) {
// optional parameters
...
},
)
Java
GenerateContentResponse response = generativeModelFutures.generateContent(
new GenerateContentRequest.Builder(
new ImagePart(bitmap),
new TextPart("textPrompt"))
// optional parameters
.build())
.get();
Memproses hasil inferensi
Jalankan inferensi dan ambil hasilnya. Anda dapat memilih untuk menunggu hasil lengkap atau melakukan streaming respons saat dibuat untuk perintah khusus teks dan multimodal.
Tindakan ini menggunakan inferensi non-streaming, yang mengambil seluruh hasil dari model AI sebelum menampilkan hasilnya:
Kotlin
// Call the AI model to generate content and store the complete // in a new variable named 'response' once it's finished val response = generativeModel.generateContent("Write a 3 sentence story about a magical dog")Java
GenerateContentResponse response = generativeModelFutures.generateContent( new GenerateContentRequest.Builder( new TextPart("Write a 3 sentence story about a magical dog.")) .build()) .get();Cuplikan berikut adalah contoh penggunaan inferensi streaming, yang mengambil hasil dalam bagian saat dibuat:
Kotlin
// Streaming inference var fullResponse = "" generativeModel.generateContentStream("Write a 3 sentence story about a magical dog").collect { chunk -> val newChunkReceived = chunk.candidates[0].text print(newChunkReceived) fullResponse += newChunkReceived }Java
// Streaming inference StringBuilder fullResponse = new StringBuilder(); generativeModelFutures.generateContent(new GenerateContentRequest.Builder( (new TextPart("Write a 3 sentence story about a magical dog"))).build(), chunk -> { Log.d(TAG, chunk); fullResponse.append(chunk); });
Untuk mengetahui informasi selengkapnya tentang inferensi streaming dan non-streaming, lihat Streaming versus non-streaming.
Pengoptimalan latensi
Untuk mengoptimalkan panggilan inferensi pertama, aplikasi Anda dapat secara opsional memanggil warmup(). Tindakan ini memuat Gemini Nano ke dalam memori dan menginisialisasi komponen runtime.
Konfigurasi opsional
Sebagai bagian dari setiap GenerateContentRequest, Anda dapat menetapkan parameter opsional berikut:
temperature: Mengontrol tingkat keacakan dalam pemilihan token.seed: Memungkinkan pembuatan hasil yang stabil dan deterministik.topK: Mengontrol keacakan dan keragaman dalam hasil.candidateCount: Meminta jumlah respons unik yang ditampilkan. Perhatikan bahwa jumlah respons yang sebenarnya mungkin tidak sama dengancandidateCountkarena respons duplikat akan otomatis dihapus.maxOutputTokens: Menentukan jumlah maksimum token yang dapat dibuat dalam respons.
Untuk panduan selengkapnya tentang cara menetapkan konfigurasi opsional, lihat
GenerateContentRequest.
Fitur dan batasan yang didukung
- Input harus kurang dari 4.000 token (atau sekitar 3.000 kata dalam bahasa Inggris). Untuk
mengetahui informasi selengkapnya, lihat referensi
countTokens. - Kasus penggunaan yang memerlukan output panjang (lebih dari 256 token) harus dihindari.
- AICore menerapkan kuota inferensi per aplikasi. Untuk mengetahui informasi selengkapnya, lihat Kuota per aplikasi.
- Bahasa berikut telah divalidasi untuk Prompt API:
- Inggris
- Korea
Masalah penyiapan umum
ML Kit GenAI API mengandalkan aplikasi Android AICore untuk mengakses Gemini Nano. Saat perangkat baru disiapkan (termasuk reset), atau aplikasi AICore baru direset (misalnya, hapus data, di-uninstal, lalu diinstal ulang), aplikasi AICore mungkin tidak memiliki cukup waktu untuk menyelesaikan inisialisasi (termasuk mendownload konfigurasi terbaru dari server). Akibatnya, ML Kit GenAI API mungkin tidak berfungsi seperti yang diharapkan. Berikut adalah pesan error penyiapan umum yang mungkin Anda lihat dan cara menanganinya:
| Contoh pesan error | Cara menangani |
| AICore gagal dengan jenis error 4-CONNECTION_ERROR dan kode error 601-BINDING_FAILURE: Layanan AICore gagal terikat. | Hal ini dapat terjadi saat Anda menginstal aplikasi menggunakan ML Kit GenAI API segera setelah penyiapan perangkat atau saat AICore di-uninstal setelah aplikasi Anda diinstal. Mengupdate aplikasi AICore, lalu menginstal ulang aplikasi Anda akan memperbaiki masalah ini. |
| AICore gagal dengan jenis error 3-PREPARATION_ERROR dan kode error 606-FEATURE_NOT_FOUND: Fitur ... tidak tersedia. |
Hal ini dapat terjadi saat AICore belum selesai mendownload konfigurasi terbaru. Saat perangkat terhubung ke internet, biasanya diperlukan waktu beberapa menit hingga beberapa jam untuk mengupdate. Memulai ulang perangkat dapat mempercepat update.
Perhatikan bahwa jika bootloader perangkat tidak terkunci, Anda juga akan melihat error ini—API ini tidak mendukung perangkat dengan bootloader yang tidak terkunci. |
| AICore gagal dengan jenis error 1-DOWNLOAD_ERROR dan kode error 0-UNKNOWN: Fitur ... gagal dengan status kegagalan 0 dan error esz: UNAVAILABLE: Tidak dapat me-resolve host ... | Pertahankan koneksi jaringan, tunggu beberapa menit, lalu coba lagi. |