Hướng dẫn: Làm quen với API Gemini


Hướng dẫn này minh hoạ cách truy cập Gemini API ngay trong ứ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 chứa các phần về các trường hợp sử dụng nâng cao (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.

Cân nhắc sử dụng 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 sử dụng khi không có mạng hoặc để tiết kiệm chi phí cho luồng người dùng thường dùng, bạn nên cân nhắc việc truy cập Gemini Nano chạy trên thiết bị. Để biết thêm thông tin, 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 hướng dẫn này, hãy đảm bảo rằng 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 Gemini API, bạn cần thiết lập dự án Android của mình, bao gồm cả việc thiết lập khoá API, thêm 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 Gemini API, bạn sẽ cần có khoá API. Nếu bạn chưa có khoá, hãy tạo một khoá trong Google AI Studio.

Tải khoá API

Bảo mật khoá API của bạn

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ữ khoá 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 quy trình quản lý phiên bản), sau đó sử dụng Trình bổ trợ Gradle bí mật 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ả các đoạn trích trong hướng dẫn này đều sử dụng phương pháp hay nhất sau đây. Ngoài ra, nếu muốn xem cách triển khai trình bổ trợ Gradle cho Khoá bí mật, bạn có thể xem ứng dụng mẫu cho SDK này hoặc dùng bản xem trước mới nhất của Android Studio Iguana có mẫu 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.7.0")
    }
    

    Java

    Đối với Java, bạn cần thêm 2 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.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. Đồ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 lệnh gọi API, bạn cần khởi chạy mô hình tạo sinh:

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

Đối với Java, bạn cũng cần khởi tạo đối tượng 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);

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

  • Sử dụng một mô hình dành riêng cho trường hợp sử dụng của bạn (ví dụ: gemini-1.5-flash 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 từng phương thức triển khai sẽ 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

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

Tạo văn bản từ dữ liệu đầu vào chỉ có văn bản

Khi câu lệnh nhập chỉ bao gồm văn bản, hãy sử dụng mô hình Gemini 1.5 hoặc mô hình Gemini 1.0 Pro có generateContent để tạo đầu ra văn bản:

Kotlin

Lưu ý 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 Kotlin Coroutine trên 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

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ề việc Sử dụng 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);

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

Gemini cung cấp nhiều mô hình có thể xử lý dữ liệu đầu vào đa phương thức (mô hình Gemini 1.5) để 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 câu lệnh nhập bao gồm cả văn bản và hình ảnh, hãy sử dụng mô hình Gemini 1.5 cùng với generateContent để tạo đầu ra văn bản:

Kotlin

Lưu ý 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 Kotlin Coroutine trên 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

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ề việc Sử dụng 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);

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

Khi sử dụng Gemini, bạn có thể tạo các cuộc trò chuyện dạng tự do ở nhiều chặng. SDK đơn giản hoá quy trình bằng cách quản lý trạng thái 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ý trò chuyện.

Để tạo một cuộc trò chuyện nhiều lượt (chẳng hạn như cuộc trò chuyện), hãy sử dụng mô hình Gemini 1.5 hoặc mô hình Gemini 1.0 Pro và bắt đầu cuộc trò chuyện bằng cách gọi startChat(). Sau đó, hãy sử dụng sendMessage() để gửi tin nhắn mới cho người dùng. 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ó hai lựa chọn có thể áp dụng 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 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 ý 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 Kotlin Coroutine trên 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

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ề việc Sử dụng 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);

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 này trả về một phản hồi sau khi hoàn tất toàn bộ quy trình tạo. Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không phải chờ toàn bộ kết quả mà thay vào đó hãy sử dụng tính năng truyền trực tuyến để xử lý một phần kết quả.

Ví dụ sau đây 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 ý 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 Kotlin Coroutine trên 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

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

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

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

Kotlin

Lưu ý 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 Kotlin Coroutine 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ề một loại Publisher từ thư viện Luồng phản ứng.

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

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 sẽ giúp bạn làm quen với việc sử dụng Gemini API. 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.

Gọi hàm

Lệnh gọi hàm giúp bạn dễ dàng nhận kết quả đầu ra dữ liệu có cấu trúc từ các mô hình tạo sinh. Sau đó, bạn có thể sử dụng những dữ liệu đầu ra này để gọi các API khác và trả về dữ liệu phản hồi liên quan cho mô hình. Nói cách khác, lệnh gọi hàm giúp bạn kết nối các mô hình tạo sinh với các hệ thống bên ngoài để nội dung được tạo có chứa thông tin mới nhất và chính xác nhất. Hãy tìm hiểu thêm trong hướng dẫn gọi hàm.

Đếm mã

Khi sử dụng các câu lệnh 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 ý 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 Kotlin Coroutine 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ề việc 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ố của mô hình và sử dụng các chế độ cài đặt an toàn.

Định cấu hình tham số của 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 một phản hồi. Mô hình có thể tạo ra kết quả khác nhau cho các giá trị tham số khác nhau. Tìm hiểu thêm về Thông số mô hình.

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

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

Bạn có thể sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được những phản hồi có thể được 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 trung bình và/hoặc cao là nội dung không an toàn trên mọi phương diện. Tìm hiểu thêm về Chế độ cài đặt an toàn.

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

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

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

Bước tiếp theo

  • Thiết kế câu lệnh là quá trình tạo các câu lệnh để gợi ra 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 thiết yếu để đảm bảo các câu trả lời chính xác, có chất lượng cao từ một mô hình ngôn ngữ. Tìm hiểu các phương pháp hay nhất để viết câu lệnh.

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

  • 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 sử dụng khi không có mạng hoặc để tiết kiệm chi phí cho luồng người dùng thường dùng, bạn nên cân nhắc việc truy cập Gemini Nano chạy trên thiết bị. Để biết thêm thông tin, hãy tham khảo hướng dẫn về Android (trên thiết bị).