Tạo văn bản trong các câu lệnh đa phương thức bằng API Gemini


Khi gọi Gemini API từ ứng dụng bằng SDK Vertex AI in Firebase, bạn có thể nhắc mô hình Gemini tạo văn bản dựa trên dữ liệu đầu vào đa phương thức. Lời nhắc đa phương thức có thể bao gồm nhiều phương thức (hoặc loại dữ liệu đầu vào), chẳng hạn như văn bản cùng với hình ảnh, tệp PDF, tệp văn bản thuần tuý, video và âm thanh.

Trong mỗi yêu cầu đa phương thức, bạn phải luôn cung cấp những thông tin sau:

Để kiểm thử và lặp lại các lời nhắc đa phương thức, bạn nên sử dụng Vertex AI Studio.

Trước khi bắt đầu

Nếu bạn chưa hoàn tất, hãy hoàn thành hướng dẫn bắt đầu sử dụng. Hướng dẫn này mô tả cách thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK, khởi chạy dịch vụ Vertex AI và tạo một thực thể GenerativeModel.

Tạo văn bản từ văn bản và một hình ảnh Tạo văn bản từ văn bản và nhiều hình ảnh Tạo văn bản từ văn bản và video

Tệp nội dung nghe nhìn mẫu

Nếu chưa có tệp nội dung đa phương tiện, bạn có thể sử dụng các tệp có sẵn công khai sau đây. Vì các tệp này được lưu trữ trong các bộ chứa không có trong dự án Firebase, nên bạn cần sử dụng định dạng https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE cho URL.

Tạo văn bản từ văn bản và một hình ảnh

Hãy đảm bảo bạn đã hoàn tất phần Trước khi bắt đầu trong hướng dẫn này trước khi thử mẫu này.

Bạn có thể gọi Gemini API bằng lời nhắc đa phương thức bao gồm cả văn bản và một tệp (chẳng hạn như hình ảnh, như trong ví dụ này). Đối với các lệnh gọi này, bạn cần sử dụng một mô hình hỗ trợ nội dung nghe nhìn trong lời nhắc (chẳng hạn như Gemini 2.0 Flash).

Hãy nhớ xem lại các yêu cầu và đề xuất đối với tệp đầu vào.

Chọn xem bạn muốn truyền trực tuyến phản hồi (generateContentStream) hay đợi phản hồi cho đến khi toàn bộ kết quả được tạo (generateContent).

Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, 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ụ này cho biết cách sử dụng generateContentStream() để truyền trực tuyến văn bản được tạo từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và một hình ảnh:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)

// Provide a prompt that includes the image specified above and text
val prompt = content {
  image(bitmap)
  text("What developer tool is this mascot from?")
}

// To stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
  print(chunk.text)
  fullResponse += chunk.text
}
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về một loại Publisher từ thư viện Luồng phản ứng.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);

// Provide a prompt that includes the image specified above and text
Content prompt = new Content.Builder()
        .addImage(bitmap)
        .addText("What developer tool is this mascot from?")
        .build();

// To stream generated text output, call generateContentStream with the prompt
Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(prompt);

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

Ngoài ra, bạn có thể chờ toàn bộ kết quả thay vì truyền trực tuyến; kết quả chỉ được trả về sau khi mô hình hoàn tất toàn bộ quá trình tạo.

Ví dụ này cho biết cách sử dụng generateContent() để tạo văn bản từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và một hình ảnh:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)

// Provide a prompt that includes the image specified above and text
val prompt = content {
  image(bitmap)
  text("What developer tool is this mascot from?")
}

// To generate text output, call generateContent with the prompt
val response = generativeModel.generateContent(prompt)
print(response.text)
Đối với Java, các phương thức trong SDK này trả về một ListenableFuture.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);

// Provide a prompt that includes the image specified above and text
Content content = new Content.Builder()
        .addImage(bitmap)
        .addText("What developer tool is this mascot from?")
        .build();

// To generate text output, call generateContent with the prompt
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ìm hiểu cách chọn một mô hình và tuỳ ý chọn một vị trí phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Tạo văn bản từ văn bản và nhiều hình ảnh

Hãy đảm bảo bạn đã hoàn tất phần Trước khi bắt đầu trong hướng dẫn này trước khi thử mẫu này.

Bạn có thể gọi Gemini API bằng các lời nhắc đa phương thức bao gồm cả văn bản và nhiều tệp (như hình ảnh, như trong ví dụ này). Đối với các lệnh gọi này, bạn cần sử dụng một mô hình hỗ trợ nội dung nghe nhìn trong lời nhắc (chẳng hạn như Gemini 2.0 Flash).

Hãy nhớ xem lại các yêu cầu và đề xuất đối với tệp đầu vào.

Chọn xem bạn muốn truyền trực tuyến phản hồi (generateContentStream) hay đợi phản hồi cho đến khi toàn bộ kết quả được tạo (generateContent).

Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, 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ụ này cho thấy cách sử dụng generateContentStream() để truyền trực tuyến văn bản được tạo từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và nhiều hình ảnh:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

// Loads an image from the app/res/drawable/ directory
val bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
val bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky_eats_pizza)

// Provide a prompt that includes the images specified above and text
val prompt = content {
    image(bitmap1)
    image(bitmap2)
    text("What's different between these pictures?")
}

// To stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
  print(chunk.text)
  fullResponse += chunk.text
}
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về một loại Publisher từ thư viện Luồng phản ứng.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky_eats_pizza);

// Provide a prompt that includes the images specified above and text
Content prompt = new Content.Builder()
    .addImage(bitmap1)
    .addImage(bitmap2)
    .addText("What's different between these pictures?")
    .build();

// To stream generated text output, call generateContentStream with the prompt
Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(prompt);

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

Ngoài ra, bạn có thể đợi toàn bộ kết quả thay vì truyền trực tuyến; kết quả chỉ được trả về sau khi mô hình hoàn tất toàn bộ quá trình tạo.

Ví dụ này cho biết cách sử dụng generateContent() để tạo văn bản từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và nhiều hình ảnh:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

// Loads an image from the app/res/drawable/ directory
val bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
val bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky_eats_pizza)

// Provide a prompt that includes the images specified above and text
val prompt = content {
  image(bitmap1)
  image(bitmap2)
  text("What is different between these pictures?")
}

// To generate text output, call generateContent with the prompt
val response = generativeModel.generateContent(prompt)
print(response.text)
Đối với Java, các phương thức trong SDK này trả về một ListenableFuture.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky_eats_pizza);

// Provide a prompt that includes the images specified above and text
Content prompt = new Content.Builder()
    .addImage(bitmap1)
    .addImage(bitmap2)
    .addText("What's different between these pictures?")
    .build();

// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
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ìm hiểu cách chọn một mô hình và tuỳ ý chọn một vị trí phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Tạo văn bản từ văn bản và video

Hãy đảm bảo bạn đã hoàn tất phần Trước khi bắt đầu trong hướng dẫn này trước khi thử mẫu này.

Bạn có thể gọi Gemini API bằng lời nhắc đa phương thức bao gồm cả(các) tệp văn bản và video (như trong ví dụ này). Đối với các lệnh gọi này, bạn cần sử dụng một mô hình hỗ trợ nội dung nghe nhìn trong lời nhắc (chẳng hạn như Gemini 2.0 Flash).

Hãy nhớ xem lại các yêu cầu và đề xuất đối với tệp đầu vào.

Chọn xem bạn muốn truyền trực tuyến phản hồi (generateContentStream) hay đợi phản hồi cho đến khi toàn bộ kết quả được tạo (generateContent).

Bạn có thể đạt được các lượt tương tác nhanh hơn bằng cách không chờ toàn bộ kết quả từ quá trình tạo mô hình, 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ụ này cho thấy cách sử dụng generateContentStream() để truyền trực tuyến văn bản được tạo từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và một video:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To stream generated text output, call generateContentStream with the prompt
    var fullResponse = ""
    generativeModel.generateContentStream(prompt).collect { chunk ->
        Log.d(TAG, chunk.text ?: "")
        fullResponse += chunk.text
    }
  }
}
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về một loại Publisher từ thư viện Luồng phản ứng.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To stream generated text output, call generateContentStream with the prompt
        Publisher<GenerateContentResponse> streamingResponse =
                model.generateContentStream(prompt);

        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) {
            }
         });
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Ngoài ra, bạn có thể chờ toàn bộ kết quả thay vì truyền trực tuyến; kết quả chỉ được trả về sau khi mô hình hoàn tất toàn bộ quá trình tạo.

Ví dụ này cho thấy cách sử dụng generateContent() để tạo văn bản từ một yêu cầu lời nhắc đa phương thức bao gồm văn bản và một video:

KotlinJava
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")

val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To generate text output, call generateContent with the prompt
    val response = generativeModel.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}
Đối với Java, các phương thức trong SDK này trả về một ListenableFuture.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To generate text output, call generateContent with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        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);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Tìm hiểu cách chọn một mô hình và tuỳ ý chọn một vị trí phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Yêu cầu và đề xuất đối với tệp đầu vào

Hãy xem phần Các tệp đầu vào được hỗ trợ và yêu cầu đối với Vertex AI Gemini API để tìm hiểu về những nội dung sau:

  • Các tuỳ chọn cung cấp tệp trong yêu cầu
  • Các loại tệp được hỗ trợ
  • Các loại MIME được hỗ trợ và cách chỉ định các loại đó
  • Yêu cầu và phương pháp hay nhất đối với tệp và yêu cầu đa phương thức

Bạn có thể làm gì khác?

Thử các tính năng khác

Tìm hiểu cách kiểm soát việc tạo nội dung

Bạn cũng có thể thử nghiệm với các câu lệnh và cấu hình mô hình bằng cách sử dụng Vertex AI Studio.

Tìm hiểu thêm về các mẫu được hỗ trợ

Tìm hiểu về các mô hình có sẵn cho nhiều trường hợp sử dụng, cũng như hạn mứcgiá của các mô hình đó.


Gửi ý kiến phản hồi về trải nghiệm của bạn với Vertex AI in Firebase