Bắt đầu sử dụng API Gemini trong ứng dụng Android (SDK ứng dụng)

Hướng dẫn này minh hoạ cách truy cập vào API Gemini ngay từ ứng dụng Android bằng SDK ứng dụng AI của Google dành cho Android. Bạn có thể dùng SDK ứng dụng này nếu không muốn làm việc trực tiếp với API REST hoặc mã phía máy chủ (như Python) để truy cập vào các mô hình Gemini trong ứng dụng Android.

Trong hướng dẫn này, bạn sẽ tìm hiểu cách thực hiện những việc sau:

Ngoài ra, hướng dẫn này còn có các phần về các trường hợp sử dụng nâng cao (chẳng hạn như đếm mã thông báo) cũng như các tuỳ chọn để kiểm soát việc tạo nội dung.

Hãy cân nhắc truy cập vào Gemini trên thiết bị

SDK ứng dụng dành cho Android được mô tả trong hướng dẫn này cho phép bạn truy cập vào các mô hình Gemini Pro chạy trên các máy chủ của Google. Đối với các trường hợp sử dụng liên quan đến việc xử lý dữ liệu nhạy cảm, khả năng hoạt động khi không có mạng hoặc để tiết kiệm chi phí cho các luồng người dùng thường dùng, bạn có thể cân nhắc việc truy cập vào Gemini Nano chạy trên thiết bị. Để biết thêm thông tin chi tiết, hãy tham khảo Hướng dẫn về Android (trên thiết bị).

Điều kiện tiên quyết

Hướng dẫn này giả định rằng bạn đã quen với việc sử dụng Android Studio để phát triển ứng dụng Android.

Để hoàn tất phần hướng dẫn này, hãy đảm bảo môi trường phát triển và ứng dụng Android của bạn đáp ứng các yêu cầu sau:

  • Android Studio (phiên bản mới nhất)
  • Ứng dụng Android của bạn phải nhắm đến API cấp 21 trở lên.

Thiết lập dự án

Trước khi gọi API Gemini, bạn cần thiết lập dự án Android, bao gồm cả việc thiết lập khoá API, thêm các phần phụ thuộc SDK vào dự án Android và khởi chạy mô hình.

Thiết lập khoá API

Để sử dụng API Gemini, bạn cần có một khoá API. Nếu bạn chưa có khoá, hãy tạo khoá trong Google AI Studio.

Lấy khoá API

Bảo mật khoá API

Bạn không nên kiểm tra khoá API trong hệ thống quản lý phiên bản của mình. Thay vào đó, bạn nên lưu trữ tệp này trong tệp local.properties (nằm trong thư mục gốc của dự án nhưng bị loại trừ khỏi hệ thống quản lý phiên bản), sau đó sử dụng trình bổ trợ Secrets Gradle cho Android để đọc khoá API dưới dạng biến Cấu hình bản dựng.

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;

Tất cả đoạn trích trong hướng dẫn này đều sử dụng phương pháp hay nhất này. Ngoài ra, nếu muốn xem cách triển khai trình bổ trợ Secrets cho Gradle, bạn có thể xem ứng dụng mẫu của SDK này hoặc sử dụng bản xem trước mới nhất của Android Studio Iguana có Gemini API Starter (bao gồm tệp local.properties để giúp bạn bắt đầu).

Thêm phần phụ thuộc SDK vào dự án

  1. Trong tệp cấu hình Gradle mô-đun (cấp ứng dụng) (như <project>/<app-module>/build.gradle.kts), hãy thêm phần phụ thuộc cho SDK AI của Google dành cho 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.3.0")
    }
    

    Java

    Đối với Java, bạn cần thêm hai thư viện bổ sung.

    dependencies {
        // ... other androidx dependencies
    
        // add the dependency for the Google AI client SDK for Android
        implementation("com.google.ai.client.generativeai:generativeai:0.3.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. Đồng bộ hoá dự án Android với các tệp Gradle.

Khởi chạy Mô hình tạo sinh

Để có thể thực hiện bất kỳ lệnh gọi API nào, bạn cần khởi động đối tượng GenerativeModel:

Kotlin

val generativeModel = GenerativeModel(
    // Use a model that's applicable for your use case (see "Implement basic use cases" below)
    modelName = "MODEL_NAME",
    // Access your API key as a Build Configuration variable (see "Set up your API key" above)
    apiKey = BuildConfig.apiKey
)

Java

Đối với Java, bạn cũng cần khởi chạy đối tượng GenerativeModelFutures.

// Use a model that's applicable for your use case (see "Implement basic use cases" below)
GenerativeModel gm = new GenerativeModel(/* modelName */ "MODEL_NAME",
// 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);

Khi chỉ định một mô hình, hãy lưu ý những điều sau:

  • Sử dụng mô hình dành riêng cho trường hợp sử dụng của bạn (ví dụ: gemini-pro-vision dành cho phương thức nhập đa phương thức). Trong hướng dẫn này, hướng dẫn cho mỗi cách triển khai liệt kê mô hình được đề xuất cho từng trường hợp sử dụng.

Triển khai các trường hợp sử dụng phổ biến

Bây giờ, dự án của bạn đã được thiết lập, bạn có thể khám phá cách sử dụng API Gemini để triển khai các trường hợp sử dụng khác nhau:

Tạo văn bản từ phương thức nhập chỉ bằng văn bản

Khi câu lệnh đầu vào chỉ bao gồm văn bản, hãy sử dụng mô hình gemini-pro với generateContent để tạo đầu ra văn bản:

Kotlin

Lưu ý rằng generateContent() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên Android.

val generativeModel = GenerativeModel(
    // For text-only input, use the gemini-pro model
    modelName = "gemini-pro",
    // 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

Xin lưu ý rằng generateContent() trả về ListenableFuture. Nếu bạn chưa hiểu rõ về API này, hãy xem tài liệu của Android về cách Sử dụng ListenableFuture.

// For text-only input, use the gemini-pro model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro",
// 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);

Tạo văn bản bằng phương thức nhập văn bản và hình ảnh (đa phương thức)

Gemini cung cấp một mô hình đa phương thức (gemini-pro-vision) để bạn có thể nhập cả văn bản và hình ảnh. Hãy nhớ xem lại các yêu cầu về hình ảnh đối với câu lệnh.

Khi lời nhắc đầu vào bao gồm cả văn bản và hình ảnh, hãy sử dụng mô hình gemini-pro-vision với generateContent để tạo đầu ra văn bản:

Kotlin

Lưu ý rằng generateContent() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên Android.

val generativeModel = GenerativeModel(
    // For text-and-images input (multimodal), use the gemini-pro-vision model
    modelName = "gemini-pro-vision",
    // 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

Xin lưu ý rằng generateContent() trả về ListenableFuture. Nếu bạn chưa hiểu rõ về API này, hãy xem tài liệu của Android về cách Sử dụng ListenableFuture.

// For text-and-images input (multimodal), use the gemini-pro-vision model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro-vision",
// 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);

Xây dựng cuộc trò chuyện nhiều lượt (trò chuyện)

Khi dùng Gemini, bạn có thể tạo các cuộc trò chuyện dạng tự do qua nhiều lượt. SDK đơn giản hoá quy trình bằng cách quản lý trạng thái của cuộc trò chuyện, vì vậy, không giống như generateContent, bạn không phải tự lưu trữ nhật ký cuộc trò chuyện.

Để tạo một cuộc trò chuyện nhiều lượt (như cuộc trò chuyện), hãy sử dụng mô hình gemini-pro và khởi động cuộc trò chuyện bằng cách gọi startChat(). Sau đó, sử dụng sendMessage() để gửi tin nhắn cho người dùng mới. Thao tác này cũng sẽ thêm tin nhắn và câu trả lời vào nhật ký trò chuyện.

Có 2 tuỳ chọn cho role liên kết với nội dung trong cuộc trò chuyện:

  • user: vai trò đưa ra lời nhắc. Giá trị này là giá trị mặc định cho các lệnh gọi sendMessage.

  • model: vai trò đưa ra câu trả lời. Bạn có thể dùng vai trò này khi gọi startChat() bằng history hiện có.

Kotlin

Lưu ý rằng generateContent() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên Android.

val generativeModel = GenerativeModel(
    // For text-only input, use the gemini-pro model
    modelName = "gemini-pro",
    // 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

Xin lưu ý rằng generateContent() trả về ListenableFuture. Nếu bạn chưa hiểu rõ về API này, hãy xem tài liệu của Android về cách Sử dụng ListenableFuture.

// For text-only input, use the gemini-pro model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro",
// 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 userMessage = new Content.Builder()
    .setRole("user")
    .addText("How many paws are in my house?")
    .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);

Sử dụng tính năng phát trực tuyến để tương tác nhanh hơn

Theo mặc định, mô hình sẽ trả về một phản hồi sau khi hoàn tất toàn bộ quá trình tạo. Bạn có thể đạt được tương tác nhanh hơn bằng cách không đợi toàn bộ kết quả, mà thay vào đó sử dụng phương thức truyền trực tuyến để xử lý một phần kết quả.

Ví dụ sau cho biết cách triển khai truyền trực tuyến bằng generateContentStream để tạo văn bản từ lời nhắc nhập văn bản và hình ảnh.

Kotlin

Lưu ý rằng generateContentStream() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên Android.

val generativeModel = GenerativeModel(
    // For text-and-image input (multimodal), use the gemini-pro-vision model
    modelName = "gemini-pro-vision",
    // 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

Các phương thức truyền trực tuyến Java trong SDK này sẽ trả về loại Publisher từ thư viện Reactive khoẻ (Luồng phản ứng).

// For text-and-images input (multimodal), use the gemini-pro-vision model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro-vision",
// 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);

final String[] fullResponse = {""};

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        fullResponse[0] += chunk;
    }

    @Override
    public void onComplete() {
        System.out.println(fullResponse[0]);
    }

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

    @Override
    public void onSubscribe(Subscription s) { }
});

Bạn có thể áp dụng phương pháp tương tự cho các trường hợp sử dụng tính năng nhập và trò chuyện chỉ bằng văn bản:

Kotlin

Lưu ý rằng generateContentStream() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên 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

Các phương thức truyền trực tuyến Java trong SDK này sẽ trả về loại Publisher từ thư viện Reactive khoẻ (Luồng phản ứng).

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

final String[] fullResponse = {""};

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        fullResponse[0] += chunk;
    }

    @Override
    public void onComplete() {
        System.out.println(fullResponse[0]);
    }

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

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

final String[] fullResponse = {""};

streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
    @Override
    public void onNext(GenerateContentResponse generateContentResponse) {
        String chunk = generateContentResponse.getText();
        fullResponse[0] += chunk;
    }

    @Override
    public void onComplete() {
        System.out.println(fullResponse[0]);
    }

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

Triển khai các trường hợp sử dụng nâng cao

Các trường hợp sử dụng phổ biến được mô tả trong phần trước của hướng dẫn này giúp bạn làm quen với việc sử dụng API Gemini. Phần này mô tả một số trường hợp sử dụng có thể được coi là nâng cao hơn.

Số lượng mã thông báo

Khi sử dụng lời nhắc dài, bạn nên đếm mã thông báo trước khi gửi bất kỳ nội dung nào đến mô hình. Các ví dụ sau đây minh hoạ cách sử dụng countTokens() cho nhiều trường hợp sử dụng:

Kotlin

Lưu ý rằng countTokens() là một hàm tạm ngưng và cần được gọi từ phạm vi Coroutine. Nếu bạn chưa hiểu rõ về Coroutine, hãy đọc bài viết Coroutine Kotlin trên 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

Xin lưu ý rằng countTokens() trả về ListenableFuture. Nếu bạn chưa hiểu rõ về API này, hãy xem tài liệu của Android về cách Sử dụng 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]));

Các tuỳ chọn kiểm soát việc tạo nội dung

Bạn có thể kiểm soát việc tạo nội dung bằng cách định cấu hình các tham số mô hình và sử dụng các chế độ cài đặt an toàn.

Định cấu hình thông số mô hình

Mọi lời nhắc bạn gửi đến mô hình đều bao gồm các giá trị tham số kiểm soát cách mô hình tạo ra một phản hồi. Mô hình này có thể tạo ra các kết quả khác nhau cho các giá trị tham số khác nhau. Tìm hiểu thêm về Tham số mô hình.

Kotlin

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

val generativeModel = GenerativeModel(
    modelName = "MODEL_NAME",
    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();

GenerativeModel gm = new GenerativeModel(
    "MODEL_NAME",
    BuildConfig.apiKey,
    generationConfig
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Sử dụng các chế độ cài đặt an toàn

Bạn có thể sử dụng các chế độ cài đặt an toàn để điều chỉnh khả năng nhận được những câu trả lời có thể bị coi là gây hại. Theo mặc định, các chế độ cài đặt an toàn sẽ chặn nội dung có xác suất là nội dung không an toàn trên mọi phương diện ở mức trung bình và/hoặc cao. Tìm hiểu thêm về Chế độ cài đặt an toàn.

Sau đây là cách đặt một chế độ cài đặt an toàn:

Kotlin

val generativeModel = GenerativeModel(
    modelName = "MODEL_NAME",
    apiKey = BuildConfig.apiKey,
    safetySettings = listOf(
        SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)
    )
)

Java

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

GenerativeModel gm = new GenerativeModel(
    "MODEL_NAME",
    BuildConfig.apiKey,
    null, // generation config is optional
    Collections.singletonList(harassmentSafety)
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bạn cũng có thể đặt nhiều chế độ cài đặt an toàn:

Kotlin

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

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

val generativeModel = GenerativeModel(
    modelName = "MODEL_NAME",
    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);

GenerativeModel gm = new GenerativeModel(
    "MODEL_NAME",
    BuildConfig.apiKey,
    null, // generation config is optional
    Arrays.asList(harassmentSafety, hateSpeechSafety)
);

GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bước tiếp theo

  • Thiết kế lời nhắc là quá trình tạo các câu lệnh để khơi gợi phản hồi mong muốn từ các mô hình ngôn ngữ. Việc viết câu lệnh có cấu trúc hợp lý là một phần cần thiết để đảm bảo câu trả lời chính xác và chất lượng cao từ mô hình ngôn ngữ. Tìm hiểu các phương pháp hay nhất để viết gợi ý.

  • Gemini cung cấp một số biến thể mô hình để đáp ứng nhu cầu của nhiều trường hợp sử dụng, chẳng hạn như loại dữ liệu đầu vào và độ phức tạp, cách triển khai cho cuộc trò chuyện hoặc các tác vụ khác về ngôn ngữ hộp thoại cũng như các quy tắc ràng buộc về kích thước. Tìm hiểu về các mô hình Gemini hiện có.

  • Gemini đưa ra các tuỳ chọn để yêu cầu tăng giới hạn tốc độ. Giới hạn tốc độ cho các mô hình Genmini Pro là 60 yêu cầu mỗi phút (RPM).

  • SDK ứng dụng dành cho Android được mô tả trong hướng dẫn này cho phép bạn truy cập vào các mô hình Gemini Pro chạy trên các máy chủ của Google. Đối với các trường hợp sử dụng liên quan đến việc xử lý dữ liệu nhạy cảm, khả năng hoạt động khi không có mạng hoặc để tiết kiệm chi phí cho các luồng người dùng thường dùng, bạn có thể cân nhắc việc truy cập vào Gemini Nano chạy trên thiết bị. Để biết thêm thông tin chi tiết, hãy tham khảo Hướng dẫn về Android (trên thiết bị).