บทแนะนำ: เริ่มต้นใช้งาน Gemini API

เริ่มต้น


บทแนะนำนี้สาธิตวิธีเข้าถึง Gemini API โดยตรงจาก แอป Android ที่ใช้ SDK ของไคลเอ็นต์ AI ของ Google สำหรับ Android คุณใช้ SDK ของไคลเอ็นต์หากคุณไม่ต้องการทำงานกับ REST API หรือโค้ดฝั่งเซิร์ฟเวอร์โดยตรง (เช่น Python) ในการเข้าถึงโมเดล Gemini ในแอป Android ของคุณ

ในบทแนะนำนี้ คุณจะได้เรียนรู้วิธีทำสิ่งต่อไปนี้

นอกจากนี้ บทแนะนำนี้ยังประกอบด้วยส่วนต่างๆ เกี่ยวกับกรณีการใช้งานขั้นสูง (เช่น โทเค็นการนับ) รวมทั้งตัวเลือกสำหรับ การควบคุมการสร้างเนื้อหา

ลองเข้าถึง Gemini ในอุปกรณ์

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

ข้อกำหนดเบื้องต้น

บทแนะนำนี้จะถือว่าคุณคุ้นเคยกับการใช้ Android Studio เพื่อ พัฒนาแอป Android

หากต้องการจบบทแนะนำนี้ โปรดตรวจสอบว่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์และ แอป Android เป็นไปตามข้อกำหนดต่อไปนี้

  • Android Studio (เวอร์ชันล่าสุด)
  • แอป Android ต้องกำหนดเป้าหมายเป็น API ระดับ 21 ขึ้นไป

ตั้งค่าโปรเจ็กต์

ก่อนที่จะเรียกใช้ Gemini API คุณต้องตั้งค่าโปรเจ็กต์ Android ซึ่ง รวมถึงการตั้งค่าคีย์ API, การเพิ่มทรัพยากร Dependency ของ SDK ในอุปกรณ์ Android โปรเจ็กต์ และการเริ่มต้นโมเดล

ตั้งค่าคีย์ API

หากต้องการใช้ Gemini API คุณจะต้องมีคีย์ API หากคุณยังไม่มี สร้างคีย์ใน Google AI Studio

รับคีย์ API

รักษาคีย์ API ให้ปลอดภัย

ขอแนะนำว่าอย่าตรวจสอบคีย์ API ในเวอร์ชันของคุณ ระบบควบคุม แต่ควรจัดเก็บไว้ในไฟล์ local.properties แทน (ซึ่งอยู่ในไดเรกทอรีรากของโครงการ แต่ไม่รวมอยู่ในเวอร์ชัน ควบคุม) แล้วใช้ ปลั๊กอินข้อมูลลับ Gradle สำหรับ Android เพื่ออ่านคีย์ API เป็นตัวแปรการกำหนดค่าบิลด์

Kotlin

// Access your API key as a Build Configuration variable
val apiKey = BuildConfig.apiKey

Java

// Access your API key as a Build Configuration variable
String apiKey = BuildConfig.apiKey;

ตัวอย่างข้อมูลทั้งหมดในบทแนะนำนี้ใช้ประโยชน์จากแนวทางปฏิบัติแนะนำนี้ นอกจากนี้ หากคุณ หากต้องการดูการใช้งานปลั๊กอิน Secrets Gradle คุณสามารถดู ตัวอย่างแอป SDK นี้หรือใช้ตัวอย่างล่าสุดของ Android Studio Iguana ซึ่งมี เทมเพลต Gemini API Starter (ซึ่งรวมถึงไฟล์ local.properties สำหรับใช้เริ่มต้น)

เพิ่มทรัพยากร Dependency ของ SDK ในโปรเจ็กต์ของคุณ

  1. ในไฟล์การกำหนดค่า Gradle แบบโมดูล (ระดับแอป) (เช่น <project>/<app-module>/build.gradle.kts) ให้เพิ่มทรัพยากร Dependency สำหรับ Google AI SDK สำหรับ Android:

    Kotlin

    dependencies {
      // ... other androidx dependencies
    
      // add the dependency for the Google AI client SDK for Android
      implementation("com.google.ai.client.generativeai:generativeai:0.9.0")
    }
    

    Java

    สำหรับ Java คุณต้องเพิ่มไลบรารีอีก 2 รายการ

    dependencies {
        // ... other androidx dependencies
    
        // add the dependency for the Google AI client SDK for Android
        implementation("com.google.ai.client.generativeai:generativeai:0.9.0")
    
        // Required for one-shot operations (to use `ListenableFuture` from Guava Android)
        implementation("com.google.guava:guava:31.0.1-android")
    
        // Required for streaming operations (to use `Publisher` from Reactive Streams)
        implementation("org.reactivestreams:reactive-streams:1.0.4")
    }
    
  2. ซิงค์โปรเจ็กต์ Android กับไฟล์ Gradle

เริ่มต้นโมเดล Generative

ก่อนเรียก API คุณต้องเริ่มต้นโมเดล Generative โดยทำดังนี้

Kotlin

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with most use cases
    modelName = "gemini-1.5-flash",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

Java

สำหรับ Java คุณต้องเริ่มต้นออบเจ็กต์ GenerativeModelFutures ด้วย

// Use a model that's applicable for your use case
// The Gemini 1.5 models are versatile and work with most use cases
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
    /* apiKey */ BuildConfig.apiKey);

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

เมื่อระบุโมเดล ให้คำนึงถึงสิ่งต่อไปนี้

  • ใช้โมเดลที่เหมาะกับ Use Case ของคุณโดยเฉพาะ (เช่น gemini-1.5-flash สำหรับการป้อนข้อมูลหลายรูปแบบ) ในคู่มือนี้ วิธีการสำหรับ โดยใช้รายการรูปแบบที่แนะนำสำหรับแต่ละกรณีการใช้งาน

ใช้ Use Case ทั่วไป

เมื่อตั้งค่าโปรเจ็กต์แล้ว คุณสามารถสำรวจโดยใช้ Gemini API เพื่อทำสิ่งต่อไปนี้ได้ ใช้กรณีการใช้งานที่แตกต่างกัน

สร้างข้อความจากการป้อนข้อมูลแบบข้อความเท่านั้น

เมื่ออินพุตพรอมต์มีเฉพาะข้อความ ให้ใช้โมเดล Gemini 1.5 หรือ โมเดล Gemini 1.0 Pro ที่มี generateContent เพื่อสร้างเอาต์พุตข้อความ:

Kotlin

โปรดทราบว่า generateContent() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
    modelName = "gemini-1.5-flash",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

โปรดทราบว่า generateContent() จะแสดงผล ListenableFuture ถ้า คุณไม่คุ้นเคยกับ API นี้ โปรดดูเอกสารประกอบของ Android เกี่ยวกับ ใช้ ListenableFuture

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
    /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Content content = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

Executor executor = // ...

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

สร้างข้อความจากการป้อนข้อความและรูปภาพ (หลายรูปแบบ)

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

เมื่ออินพุตพรอมต์มีทั้งข้อความและรูปภาพ ให้ใช้โมเดล Gemini 1.5 ที่มี generateContent เพื่อสร้างเอาต์พุตข้อความ:

Kotlin

โปรดทราบว่า generateContent() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
    modelName = "gemini-1.5-flash",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

val image1: Bitmap = // ...
val image2: Bitmap = // ...

val inputContent = content {
    image(image1)
    image(image2)
    text("What's different between these pictures?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)

Java

โปรดทราบว่า generateContent() จะแสดงผล ListenableFuture ถ้า คุณไม่คุ้นเคยกับ API นี้ โปรดดูเอกสารประกอบของ Android เกี่ยวกับ ใช้ ListenableFuture

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
    /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap image1 = // ...
Bitmap image2 = // ...

Content content = new Content.Builder()
    .addText("What's different between these pictures?")
    .addImage(image1)
    .addImage(image2)
    .build();

Executor executor = // ...

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

สร้างการสนทนาแบบผลัดกันเล่น (แชท)

การใช้ Gemini ช่วยให้คุณสร้างการสนทนาในรูปแบบอิสระในหลายๆ รอบได้ SDK ทำให้กระบวนการง่ายขึ้นโดยการจัดการสถานะของการสนทนา ซึ่งต่างจาก เมื่อใช้ generateContent คุณจะไม่ต้องจัดเก็บประวัติการสนทนา ตัวคุณเอง

หากต้องการสร้างการสนทนาแบบหลายรอบ (เช่น แชท) ให้ใช้โมเดล Gemini 1.5 หรือ Gemini 1.0 Pro และเริ่มแชทโดยโทรหา startChat() จากนั้นใช้ sendMessage() เพื่อส่งข้อความของผู้ใช้ใหม่ ซึ่งจะต่อท้ายด้วย และการตอบกลับประวัติการแชท

มี 2 ตัวเลือกที่เป็นไปได้สำหรับ role ที่เชื่อมโยงกับเนื้อหาใน การสนทนา:

  • user: บทบาทที่แสดงข้อความแจ้ง ค่านี้เป็นค่าเริ่มต้นสำหรับ sendMessage สาย

  • model: บทบาทที่ให้คำตอบ บทบาทนี้สามารถใช้ได้เมื่อ กำลังโทรหา startChat() ด้วย history ปัจจุบัน

Kotlin

โปรดทราบว่า generateContent() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat)
    modelName = "gemini-1.5-flash",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

val chat = generativeModel.startChat(
    history = listOf(
        content(role = "user") { text("Hello, I have 2 dogs in my house.") },
        content(role = "model") { text("Great to meet you. What would you like to know?") }
    )
)

chat.sendMessage("How many paws are in my house?")

Java

โปรดทราบว่า generateContent() จะแสดงผล ListenableFuture ถ้า คุณไม่คุ้นเคยกับ API นี้ โปรดดูเอกสารประกอบของ Android เกี่ยวกับ ใช้ ListenableFuture

// The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat)
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
    /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder userMessageBuilder = new Content.Builder();
userMessageBuilder.setRole("user");
userMessageBuilder.addText("How many paws are in my house?");
Content userMessage = userMessageBuilder.build();

Executor executor = // ...

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(userMessage);

Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

ใช้สตรีมมิงเพื่อการโต้ตอบที่เร็วขึ้น

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

ตัวอย่างต่อไปนี้จะแสดงวิธีใช้สตรีมมิงกับ generateContentStream เพื่อสร้างข้อความจากพรอมต์การป้อนข้อความและรูปภาพ

Kotlin

โปรดทราบว่า generateContentStream() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
    modelName = "gemini-1.5-flash",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

val image1: Bitmap = // ...
val image2: Bitmap = // ...

val inputContent = content {
    image(image1)
    image(image2)
    text("What's the difference between these pictures?")
}

var fullResponse = ""
generativeModel.generateContentStream(inputContent).collect { chunk ->
    print(chunk.text)
    fullResponse += chunk.text
}

Java

เมธอดสตรีมมิงของ Java ใน SDK นี้แสดงผลประเภท Publisher จากสตรีมเชิงรับ ไลบรารี

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
    /* apiKey */ BuildConfig.apiKey);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap image1 = // ...
Bitmap image2 = // ...

Content content = new Content.Builder()
    .addText("What's different between these pictures?")
    .addImage(image1)
    .addImage(image2)
    .build();

Publisher<GenerateContentResponse> streamingResponse =
    model.generateContentStream(content);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
    }

    @Override
    public void onComplete() {
        System.out.println(outputContent);
    }

    @Override
    public void onError(Throwable t) {
        t.printStackTrace();
    }

    @Override
    public void onSubscribe(Subscription s) {
      s.request(Long.MAX_VALUE);
    }
});

คุณสามารถใช้วิธีที่คล้ายกันสำหรับการป้อนข้อความเท่านั้นและกรณีการใช้งานแชทได้ ดังนี้

Kotlin

โปรดทราบว่า generateContentStream() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

// Use streaming with text-only input
generativeModel.generateContentStream(inputContent).collect { chunk ->
    print(chunk.text)
}
// Use streaming with multi-turn conversations (like chat)
val chat = generativeModel.startChat()
chat.sendMessageStream(inputContent).collect { chunk ->
    print(chunk.text)
}

Java

เมธอดสตรีมมิงของ Java ใน SDK นี้แสดงผลประเภท Publisher จากสตรีมเชิงรับ ไลบรารี

// Use streaming with text-only input
Publisher<GenerateContentResponse> streamingResponse =
    model.generateContentStream(inputContent);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
    }

    @Override
    public void onComplete() {
        System.out.println(outputContent);
    }

    @Override
    public void onSubscribe(Subscription s) {
      s.request(Long.MAX_VALUE);
    }

    // ... other methods omitted for brevity
});
// Use streaming with multi-turn conversations (like chat)
ChatFutures chat = model.startChat(history);

Publisher<GenerateContentResponse> streamingResponse =
    chat.sendMessageStream(inputContent);

StringBuilder outputContent = new StringBuilder();

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        outputContent.append(chunk);
    }

    @Override
    public void onComplete() {
        System.out.println(outputContent);
    }

    @Override
    public void onSubscribe(Subscription s) {
      s.request(Long.MAX_VALUE);
    }

    // ... other methods omitted for brevity
});

ใช้ Use Case ขั้นสูง

กรณีการใช้งานทั่วไปที่อธิบายไว้ในส่วนก่อนหน้าของความช่วยเหลือเกี่ยวกับบทแนะนำนี้ ที่คุณจะเริ่มคุ้นเคยกับการใช้ Gemini API ส่วนนี้อธิบายถึงบางส่วน Use Case ที่อาจถือว่าเป็น Use Case ขั้นสูงกว่า

กำลังเรียกฟังก์ชัน

การเรียกฟังก์ชันช่วยให้คุณได้รับเอาต์พุตของ Structured Data ได้ง่ายขึ้น โมเดล Generative จากนั้นคุณสามารถใช้เอาต์พุตเหล่านี้เพื่อเรียกใช้ API อื่นๆ และแสดงผล ข้อมูลการตอบสนองที่เกี่ยวข้องกับโมเดล กล่าวอีกนัยหนึ่งคือ การเรียกฟังก์ชันช่วยให้ คุณเชื่อมต่อโมเดล Generative กับระบบภายนอกเพื่อให้เนื้อหาที่สร้างขึ้น ประกอบด้วยข้อมูลล่าสุดและถูกต้อง ดูข้อมูลเพิ่มเติมใน บทแนะนำการเรียกใช้ฟังก์ชัน

นับโทเค็น

การนับโทเค็นก่อนส่งอาจมีประโยชน์เมื่อใช้ข้อความแจ้งที่ยาว ของเนื้อหากับโมเดล ตัวอย่างต่อไปนี้จะแสดงวิธีใช้ countTokens() สำหรับกรณีการใช้งานต่างๆ ดังนี้

Kotlin

โปรดทราบว่า countTokens() เป็นฟังก์ชันการระงับและจำเป็นต้อง ที่เรียกใช้จากขอบเขต Coroutine หากคุณไม่คุ้นเคยกับ Coroutines โปรดอ่าน Kotlin Coroutines ใน Android

// For text-only input
val (totalTokens) = generativeModel.countTokens("Write a story about a magic backpack.")

// For text-and-image input (multi-modal)
val multiModalContent = content {
    image(image1)
    image(image2)
    text("What's the difference between these pictures?")
}

val (totalTokens) = generativeModel.countTokens(multiModalContent)

// For multi-turn conversations (like chat)
val history = chat.history
val messageContent = content { text("This is the message I intend to send")}
val (totalTokens) = generativeModel.countTokens(*history.toTypedArray(), messageContent)

Java

โปรดทราบว่า countTokens() จะแสดงผล ListenableFuture ถ้า คุณไม่คุ้นเคยกับ API นี้ โปรดดูเอกสารประกอบของ Android เกี่ยวกับ ใช้ ListenableFuture

Content text = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

Executor executor = // ...

// For text-only input
ListenableFuture<CountTokensResponse> countTokensResponse = model.countTokens(text);

Futures.addCallback(countTokensResponse, new FutureCallback<CountTokensResponse>() {
    @Override
    public void onSuccess(CountTokensResponse result) {
        int totalTokens = result.getTotalTokens();
        System.out.println("TotalTokens = " + totalTokens);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

// For text-and-image input
Bitmap image1 = // ...
Bitmap image2 = // ...

Content multiModalContent = new Content.Builder()
    .addImage(image1)
    .addImage(image2)
    .addText("What's different between these pictures?")
    .build();

ListenableFuture<CountTokensResponse> countTokensResponse = model.countTokens(multiModalContent);

// For multi-turn conversations (like chat)
List<Content> history = chat.getChat().getHistory();

Content messageContent = new Content.Builder()
    .addText("This is the message I intend to send")
    .build();

Collections.addAll(history, messageContent);

ListenableFuture<CountTokensResponse> countTokensResponse = model.countTokens(history.toArray(new Content[0]));

ตัวเลือกในการควบคุมการสร้างเนื้อหา

คุณสามารถควบคุมการสร้างเนื้อหาได้โดยกำหนดค่าพารามิเตอร์โมเดลและ การตั้งค่าความปลอดภัย

กำหนดค่าพารามิเตอร์โมเดล

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

Kotlin

val config = generationConfig {
    temperature = 0.9f
    topK = 16
    topP = 0.1f
    maxOutputTokens = 200
    stopSequences = listOf("red")
}

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with most use cases
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey,
    generationConfig = config
)

Java

GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.temperature = 0.9f;
configBuilder.topK = 16;
configBuilder.topP = 0.1f;
configBuilder.maxOutputTokens = 200;
configBuilder.stopSequences = Arrays.asList("red");

GenerationConfig generationConfig = configBuilder.build();

// The Gemini 1.5 models are versatile and work with most use cases
GenerativeModel gm = new GenerativeModel(
    "gemini-1.5-flash",
    BuildConfig.apiKey,
    generationConfig
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

ใช้การตั้งค่าความปลอดภัย

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

วิธีตั้งค่าความปลอดภัย 1 รายการมีดังนี้

Kotlin

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with most use cases
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey,
    safetySettings = listOf(
        SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)
    )
)

Java

SafetySetting harassmentSafety = new SafetySetting(HarmCategory.HARASSMENT,
    BlockThreshold.ONLY_HIGH);

// The Gemini 1.5 models are versatile and work with most use cases
GenerativeModel gm = new GenerativeModel(
    "gemini-1.5-flash",
    BuildConfig.apiKey,
    null, // generation config is optional
    Collections.singletonList(harassmentSafety)
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

นอกจากนี้ คุณยังสามารถตั้งค่าความปลอดภัยได้มากกว่า 1 รายการ ดังนี้

Kotlin

val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

val hateSpeechSafety = SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE)

val generativeModel = GenerativeModel(
    // The Gemini 1.5 models are versatile and work with most use cases
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey,
    safetySettings = listOf(harassmentSafety, hateSpeechSafety)
)

Java

SafetySetting harassmentSafety = new SafetySetting(HarmCategory.HARASSMENT,
    BlockThreshold.ONLY_HIGH);

SafetySetting hateSpeechSafety = new SafetySetting(HarmCategory.HATE_SPEECH,
    BlockThreshold.MEDIUM_AND_ABOVE);

// The Gemini 1.5 models are versatile and work with most use cases
GenerativeModel gm = new GenerativeModel(
    "gemini-1.5-flash",
    BuildConfig.apiKey,
    null, // generation config is optional
    Arrays.asList(harassmentSafety, hateSpeechSafety)
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

ขั้นตอนถัดไป

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

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

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