เริ่มต้นใช้งาน Prompt API

หน้านี้จะอธิบายวิธีการทำสิ่งต่อไปนี้

  • กำหนดค่าโปรเจ็กต์เพื่อใช้ Prompt API
  • ระบุอินพุตแบบข้อความเท่านั้นและรับคำตอบ
  • ระบุอินพุตรูปภาพพร้อมอินพุตข้อความที่เกี่ยวข้องและรับคำตอบ

ดูรายละเอียดเพิ่มเติมเกี่ยวกับ Prompt API ได้ที่เอกสารอ้างอิงสำหรับ Kotlin (com.google.mlkit.genai.prompt) และ Java (com.google.mlkit.genai.prompt.java, com.google.mlkit.genai.prompt)

กำหนดค่าโปรเจ็กต์

เพิ่ม ML Kit Prompt API เป็นทรัพยากร Dependency ในการกำหนดค่า build.gradle ดังนี้

implementation("com.google.mlkit:genai-prompt:1.0.0-beta4")

หากต้องการคำตอบในรูปแบบที่เฉพาะเจาะจงโดยใช้ Structured Output API คุณจะต้องกำหนดค่า KSP และเพิ่มทรัพยากร Dependency เพิ่มเติม โปรดดูรายละเอียดที่หัวข้อสร้างเอาต์พุตที่มีโครงสร้าง

ใช้โมเดล Generative

หากต้องการใช้โค้ดในโปรเจ็กต์ ให้ทำตามขั้นตอนต่อไปนี้

  • สร้างออบเจ็กต์ generativeModel โดยทำดังนี้

    Kotlin

    // Get a GenerativeModel instance
    val generativeModel = Generation.getClient()
    

    Java

    // Get a GenerativeModel instance
    GenerativeModelFutures generativeModelFutures = GenerativeModelFutures
        .from(Generation.INSTANCE.getClient());
    
  • ตรวจสอบว่า Gemini Nano AVAILABLE, DOWNLOADABLE หรือ UNAVAILABLE จากนั้นดาวน์โหลดฟีเจอร์หากดาวน์โหลดได้ โดยทำดังนี้

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

ระบุอินพุตแบบข้อความเท่านั้น

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

หรือจะเพิ่มพารามิเตอร์ที่ไม่บังคับต่อไปนี้ก็ได้

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับพารามิเตอร์ที่ไม่บังคับได้ที่การกำหนดค่าที่ไม่บังคับ

ระบุอินพุตหลายรูปแบบ (รูปภาพและข้อความ)

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

Kotlin

val response = generativeModel.generateContent(
    generateContentRequest(ImagePart(bitmap1), ImagePart(bitmap2), TextPart(textPrompt)) {
        // optional parameters
        ...
    },
)

Java

GenerateContentResponse response = generativeModelFutures.generateContent(
    new GenerateContentRequest.Builder(
        new Content.Builder()
            .addPart(new ImagePart(bitmap1))
            .addPart(new ImagePart(bitmap2))
            .addPart(new TextPart("textPrompt"))
            .build())
    // optional parameters
    .build())
.get();

ประมวลผลผลลัพธ์การอนุมาน

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

    • ซึ่งจะใช้การอนุมานแบบไม่สตรีมมิง ซึ่งจะดึงผลลัพธ์ทั้งหมดจากโมเดล AI ก่อนที่จะแสดงผลลัพธ์

    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();
    
    • ข้อมูลโค้ดต่อไปนี้เป็นตัวอย่างการใช้การอนุมานแบบสตรีมมิง ซึ่งจะดึงผลลัพธ์เป็นกลุ่มๆ ขณะที่สร้างขึ้น

    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);
            });
    

ดูข้อมูลเพิ่มเติมเกี่ยวกับการอนุมานแบบสตรีมมิงและไม่ใช่สตรีมมิงได้ที่สตรีมมิงเทียบกับไม่ใช่สตรีมมิง

การเพิ่มประสิทธิภาพเวลาในการตอบสนอง

หากต้องการเพิ่มประสิทธิภาพสำหรับการเรียกใช้การอนุมานครั้งแรก แอปพลิเคชันของคุณอาจเรียกใช้ warmup() ได้ (ไม่บังคับ) ซึ่งจะโหลด Gemini Nano ลงในหน่วยความจำและเริ่มต้นคอมโพเนนต์รันไทม์

การกำหนดค่าที่ไม่บังคับ

คุณสามารถตั้งค่าพารามิเตอร์ที่ไม่บังคับต่อไปนี้เป็นส่วนหนึ่งของ GenerateContentRequest แต่ละรายการได้

  • temperature : ควบคุมระดับความสุ่มในการเลือกโทเค็น
  • seed : ช่วยให้สร้างผลลัพธ์ที่เสถียรและเป็นเชิงกำหนดได้
  • topK : ควบคุมความสุ่มและความหลากหลายในผลลัพธ์
  • candidateCount : ขอจำนวนคำตอบที่ไม่ซ้ำกันที่แสดงผล โปรดทราบว่าจำนวนคำตอบที่แน่นอนอาจไม่เท่ากับ candidateCount เนื่องจากระบบจะนำคำตอบที่ซ้ำกันออกโดยอัตโนมัติ
  • maxOutputTokens : กำหนดจำนวนโทเค็นสูงสุดที่สร้างได้ในคำตอบ

ดูคำแนะนำเพิ่มเติมเกี่ยวกับการตั้งค่าการกำหนดค่าที่ไม่บังคับได้ที่ GenerateContentRequest

ฟีเจอร์ที่รองรับและข้อจำกัด

  • ข้อมูลที่ป้อนต้องมีโทเค็นไม่เกิน 4,000 รายการ (หรือประมาณ 3,000 คำในภาษาอังกฤษ) ดูข้อมูลเพิ่มเติมได้ที่ข้อมูลอ้างอิง countTokens
  • ควรหลีกเลี่ยงกรณีการใช้งานที่ต้องใช้เอาต์พุตแบบยาว (มากกว่า 4,000 โทเค็น)
  • AICore บังคับใช้โควต้าการอนุมานต่อแอป ดูข้อมูลเพิ่มเติมได้ที่โควต้าต่อแอปพลิเคชัน

ปัญหาการตั้งค่าที่พบบ่อย

GenAI API ของ ML Kit อาศัยแอป Android AICore เพื่อเข้าถึง Gemini Nano เมื่อเพิ่งตั้งค่าอุปกรณ์ (รวมถึงรีเซ็ต) หรือเพิ่งรีเซ็ตแอป AICore (เช่น ล้างข้อมูล ถอนการติดตั้งแล้วติดตั้งอีกครั้ง) แอป AICore อาจมีเวลาไม่เพียงพอในการเริ่มต้นระบบให้เสร็จสมบูรณ์ (รวมถึงการดาวน์โหลดการกำหนดค่าล่าสุดจากเซิร์ฟเวอร์) ด้วยเหตุนี้ GenAI API ของ ML Kit จึงอาจไม่ทำงานตามที่คาดไว้ ข้อความแสดงข้อผิดพลาดในการตั้งค่าที่พบบ่อยซึ่งคุณอาจเห็นและวิธีจัดการมีดังนี้

ตัวอย่างข้อความแสดงข้อผิดพลาด วิธีรับมือ
AICore ไม่สำเร็จโดยมีข้อผิดพลาดประเภท 4-CONNECTION_ERROR และรหัสข้อผิดพลาด 601-BINDING_FAILURE: บริการ AICore เชื่อมโยงไม่สำเร็จ กรณีนี้อาจเกิดขึ้นเมื่อคุณติดตั้งแอปโดยใช้ GenAI API ของ ML Kit ทันทีหลังจากตั้งค่าอุปกรณ์ หรือเมื่อถอนการติดตั้ง AICore หลังจากติดตั้งแอปแล้ว การอัปเดตแอป AICore แล้วติดตั้งแอปอีกครั้งน่าจะช่วยแก้ปัญหาได้
AICore ไม่สำเร็จโดยมีข้อผิดพลาดประเภท 3-PREPARATION_ERROR และรหัสข้อผิดพลาด 606-FEATURE_NOT_FOUND: ฟีเจอร์ ... ไม่พร้อมใช้งาน กรณีนี้อาจเกิดขึ้นเมื่อ AICore ยังดาวน์โหลดการกำหนดค่าล่าสุดไม่เสร็จ เมื่ออุปกรณ์เชื่อมต่ออินเทอร์เน็ต โดยปกติแล้วจะใช้เวลาอัปเดต 2-3 นาทีถึง 2-3 ชั่วโมง การรีสตาร์ทอุปกรณ์จะช่วยให้การอัปเดตเร็วขึ้น

โปรดทราบว่าหาก Bootloader ของอุปกรณ์ปลดล็อกอยู่ คุณจะเห็นข้อผิดพลาดนี้ด้วย เนื่องจาก API นี้ไม่รองรับอุปกรณ์ที่มี Bootloader ที่ปลดล็อกแล้ว
AICore ไม่สำเร็จโดยมีประเภทข้อผิดพลาด 1-DOWNLOAD_ERROR และรหัสข้อผิดพลาด 0-UNKNOWN: ฟีเจอร์ ... ไม่สำเร็จโดยมีสถานะความล้มเหลว 0 และข้อผิดพลาด esz: UNAVAILABLE: ไม่สามารถแปลงโฮสต์ ... เชื่อมต่อเครือข่ายไว้ รอสักครู่ แล้วลองอีกครั้ง