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

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

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

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

[ไม่บังคับ] ทดสอบพรอมต์ด้วยโมเดล Gemma 3n

ก่อนการใช้งาน ให้ลองทดสอบพรอมต์ใน AI Studio ด้วยโมเดล Gemma 3n E4B เอาต์พุตของ Gemma 3n คาดว่าจะคล้ายกับเอาต์พุตจาก nano-v3 มาก

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

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

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

ใช้โมเดล 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() ฟังก์ชัน โดยพรอมต์ข้อความจะเป็นคำถามหรือคำสั่งที่เกี่ยวข้องกับ รูปภาพ

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

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

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

    • ซึ่งจะใช้การอนุมานแบบไม่สตรีมมิง ซึ่งดึงผลลัพธ์ทั้งหมดจากโมเดล 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
  • ควรหลีกเลี่ยง Use Case ที่ต้องมีเอาต์พุตยาว (มากกว่า 256 โทเค็น)
  • AICore บังคับใช้โควต้าการอนุมานต่อแอป ดูข้อมูลเพิ่มเติมได้ที่โควต้า ต่อแอปพลิเคชัน
  • ภาษาต่อไปนี้ได้รับการตรวจสอบแล้วสำหรับ Prompt API
    • อังกฤษ
    • เกาหลี

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

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

ตัวอย่างข้อความแสดงข้อผิดพลาด วิธีจัดการ
AICore ไม่สำเร็จโดยมีข้อผิดพลาดประเภท 4-CONNECTION_ERROR และรหัสข้อผิดพลาด 601-BINDING_FAILURE: บริการ AICore เชื่อมโยงไม่สำเร็จ ปัญหานี้อาจเกิดขึ้นเมื่อคุณติดตั้งแอปโดยใช้ ML Kit GenAI API ทันทีหลังจากตั้งค่าอุปกรณ์ หรือเมื่อถอนการติดตั้ง 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: แก้ไขโฮสต์ ... ไม่ได้ เชื่อมต่อเครือข่ายไว้ รอสักครู่ แล้วลองอีกครั้ง