บทแนะนำ: เริ่มต้นใช้งาน 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 (ซึ่งอยู่ในไดเรกทอรีรูทของโปรเจ็กต์ แต่ไม่รวมอยู่ในการควบคุมเวอร์ชัน) แทน จากนั้นใช้ปลั๊กอิน Secrets 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 สำหรับ AI SDK ของ Google สำหรับ 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.7.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.7.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 มากขึ้น ส่วนนี้อธิบายกรณีการใช้งานที่อาจถือว่าเป็นขั้นสูงขึ้น

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

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