Membuat teks dari perintah multimodal menggunakan Gemini API
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Saat memanggil Gemini API dari aplikasi menggunakan Vertex AI in Firebase SDK,
Anda dapat meminta model Gemini untuk membuat teks berdasarkan input multimodal.
Perintah multimodal dapat mencakup beberapa modalitas (atau jenis input),
seperti teks beserta gambar, PDF, file teks biasa, video, dan audio.
Dalam setiap permintaan multimodal, Anda harus selalu memberikan hal berikut:
File. Anda dapat memberikan file sebagai data inline (seperti yang ditunjukkan di halaman ini) atau menggunakan URL atau URI-nya.
Untuk menguji dan melakukan iterasi pada perintah multimodal, sebaiknya gunakan
Vertex AI Studio.
Opsi lain untuk menggunakan Gemini API
Secara opsional, bereksperimenlah dengan versi "Google AI" alternatif dari
Gemini API
Dapatkan akses tanpa biaya
(dalam batas dan jika tersedia) menggunakan
Google AI Studio
dan
SDK klien Google AI.
SDK ini harus digunakan untuk hanya membuat prototipe di aplikasi seluler dan web.
Jika Anda belum melakukannya, selesaikan panduan memulai, yang menjelaskan cara menyiapkan project Firebase, menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan Vertex AI, dan membuat instance GenerativeModel.
Jika belum memiliki file media, Anda dapat menggunakan file berikut yang tersedia secara publik. Karena file ini disimpan di bucket yang tidak ada dalam project Firebase Anda, Anda harus menggunakan format https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE untuk URL.
Gambar: https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg
dengan jenis MIME image/jpeg.
Lihat atau download gambar ini.
PDF: https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf
dengan jenis MIME application/pdf.
Lihat atau download PDF ini.
Video: https://storage.googleapis.com/cloud-samples-data/video/animals.mp4
dengan jenis MIME video/mp4.
Tonton atau download video ini.
Audio: https://storage.googleapis.com/cloud-samples-data/generative-ai/audio/pixel.mp3
dengan jenis MIME audio/mp3.
Dengarkan atau download audio ini.
Membuat teks dari teks dan satu gambar
Pastikan Anda telah menyelesaikan bagian Sebelum memulai
dalam panduan ini sebelum mencoba contoh ini.
Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan
teks dan satu file (seperti gambar, seperti yang ditunjukkan dalam contoh ini).
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu gambar:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")guardletimage=UIImage(systemName:"bicycle")else{fatalError()}// Provide a text prompt to include with the imageletprompt="What's in this picture?"// To generate text output, call generateContent and pass in the promptletresponse=tryawaitmodel.generateContent(image,prompt)print(response.text??"No text in response.")
Kotlin
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu gambar:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")// Loads an image from the app/res/drawable/ directoryvalbitmap:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky)// Provide a prompt that includes the image specified above and textvalprompt=content{image(bitmap)text("What developer tool is this mascot from?")}// To generate text output, call generateContent with the promptvalresponse=generativeModel.generateContent(prompt)print(response.text)
Java
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu gambar:
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);Bitmapbitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sparky);// Provide a prompt that includes the image specified above and textContentcontent=newContent.Builder().addImage(bitmap).addText("What developer tool is this mascot from?").build();// To generate text output, call generateContent with the promptListenableFuture<GenerateContentResponse>response=model.generateContent(content);Futures.addCallback(response,newFutureCallback<GenerateContentResponse>(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){t.printStackTrace();}},executor);
Web
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu gambar:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the imageconstprompt="What's different between these pictures?";constfileInputEl=document.querySelector("input[type=file]");constimagePart=awaitfileToGenerativePart(fileInputEl.files[0]);// To generate text output, call generateContent with the text and imageconstresult=awaitmodel.generateContent([prompt,imagePart]);constresponse=result.response;consttext=response.text();console.log(text);}run();
Dart
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu gambar:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');// Provide a text prompt to include with the imagefinalprompt=TextPart("What's in the picture?");// Prepare images for inputfinalimage=awaitFile('image0.jpg').readAsBytes();finalimagePart=InlineDataPart('image/jpeg',image);// To generate text output, call generateContent with the text and imagefinalresponse=awaitmodel.generateContent([Content.multi([prompt,imagePart])]);print(response.text);
Pelajari cara memilih model
dan secara opsional lokasi
yang sesuai untuk kasus penggunaan dan aplikasi Anda.
Membuat teks dari teks dan beberapa gambar
Pastikan Anda telah menyelesaikan bagian Sebelum memulai
dalam panduan ini sebelum mencoba contoh ini.
Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan
teks dan beberapa file (seperti gambar, seperti yang ditunjukkan dalam contoh ini).
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
beberapa gambar:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")guardletimage1=UIImage(systemName:"car")else{fatalError()}guardletimage2=UIImage(systemName:"car.2")else{fatalError()}// Provide a text prompt to include with the imagesletprompt="What's different between these pictures?"// To generate text output, call generateContent and pass in the promptletresponse=tryawaitmodel.generateContent(image1,image2,prompt)print(response.text??"No text in response.")
Kotlin
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
beberapa gambar:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")// Loads an image from the app/res/drawable/ directoryvalbitmap1:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky)valbitmap2:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky_eats_pizza)// Provide a prompt that includes the images specified above and textvalprompt=content{image(bitmap1)image(bitmap2)text("What is different between these pictures?")}// To generate text output, call generateContent with the promptvalresponse=generativeModel.generateContent(prompt)print(response.text)
Java
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
beberapa gambar:
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);Bitmapbitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.sparky);Bitmapbitmap2=BitmapFactory.decodeResource(getResources(),R.drawable.sparky_eats_pizza);// Provide a prompt that includes the images specified above and textContentprompt=newContent.Builder().addImage(bitmap1).addImage(bitmap2).addText("What's different between these pictures?").build();// To generate text output, call generateContent with the promptListenableFuture<GenerateContentResponse>response=model.generateContent(prompt);Futures.addCallback(response,newFutureCallback<GenerateContentResponse>(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){t.printStackTrace();}},executor);
Web
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
beberapa gambar:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the imagesconstprompt="What's different between these pictures?";// Prepare images for inputconstfileInputEl=document.querySelector("input[type=file]");constimageParts=awaitPromise.all([...fileInputEl.files].map(fileToGenerativePart));// To generate text output, call generateContent with the text and imagesconstresult=awaitmodel.generateContent([prompt,...imageParts]);constresponse=result.response;consttext=response.text();console.log(text);}run();
Dart
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
beberapa gambar:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');final(firstImage,secondImage)=await(File('image0.jpg').readAsBytes(),File('image1.jpg').readAsBytes()).wait;// Provide a text prompt to include with the imagesfinalprompt=TextPart("What's different between these pictures?");// Prepare images for inputfinalimageParts=[InlineDataPart('image/jpeg',firstImage),InlineDataPart('image/jpeg',secondImage),];// To generate text output, call generateContent with the text and imagesfinalresponse=awaitmodel.generateContent([Content.multi([prompt,...imageParts])]);print(response.text);
Pelajari cara memilih model
dan secara opsional lokasi
yang sesuai untuk kasus penggunaan dan aplikasi Anda.
Membuat teks dari teks dan video
Pastikan Anda telah menyelesaikan bagian Sebelum memulai
dalam panduan ini sebelum mencoba contoh ini.
Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan
file teks dan video (seperti yang ditunjukkan dalam contoh ini).
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu video:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")// Provide the video as `Data` with the appropriate MIME type.letvideo=InlineDataPart(data:tryData(contentsOf:videoURL),mimeType:"video/mp4")// Provide a text prompt to include with the videoletprompt="What is in the video?"// To generate text output, call generateContent with the text and videoletresponse=tryawaitmodel.generateContent(video,prompt)print(response.text??"No text in response.")
Kotlin
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu video:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")valcontentResolver=applicationContext.contentResolvercontentResolver.openInputStream(videoUri).use{stream->stream?.let{valbytes=stream.readBytes()// Provide a prompt that includes the video specified above and textvalprompt=content{inlineData(bytes,"video/mp4")text("What is in the video?")}// To generate text output, call generateContent with the promptvalresponse=generativeModel.generateContent(prompt)Log.d(TAG,response.text?:"")}}
Java
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu video:
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);ContentResolverresolver=getApplicationContext().getContentResolver();try(InputStreamstream=resolver.openInputStream(videoUri)){FilevideoFile=newFile(newURI(videoUri.toString()));intvideoSize=(int)videoFile.length();byte[]videoBytes=newbyte[videoSize];if(stream!=null){stream.read(videoBytes,0,videoBytes.length);stream.close();// Provide a prompt that includes the video specified above and textContentprompt=newContent.Builder().addInlineData(videoBytes,"video/mp4").addText("What is in the video?").build();// To generate text output, call generateContent with the promptListenableFuture<GenerateContentResponse>response=model.generateContent(prompt);Futures.addCallback(response,newFutureCallback<GenerateContentResponse>(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){t.printStackTrace();}},executor);}}catch(IOExceptione){e.printStackTrace();}catch(URISyntaxExceptione){e.printStackTrace();}
Web
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu video:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the videoconstprompt="What do you see?";constfileInputEl=document.querySelector("input[type=file]");constvideoPart=awaitfileToGenerativePart(fileInputEl.files[0]);// To generate text output, call generateContent with the text and videoconstresult=awaitmodel.generateContent([prompt,videoPart]);constresponse=result.response;consttext=response.text();console.log(text);}run();
Dart
Anda dapat memanggil
generateContent()
untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan
satu video:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');// Provide a text prompt to include with the videofinalprompt=TextPart("What's in the video?");// Prepare video for inputfinalvideo=awaitFile('video0.mp4').readAsBytes();// Provide the video as `Data` with the appropriate mimetypefinalvideoPart=InlineDataPart('video/mp4',video);// To generate text output, call generateContent with the text and imagesfinalresponse=awaitmodel.generateContent([Content.multi([prompt,...videoPart])]);print(response.text);
Pelajari cara memilih model
dan secara opsional lokasi
yang sesuai untuk kasus penggunaan dan aplikasi Anda.
Menampilkan respons secara bertahap
Pastikan Anda telah menyelesaikan bagian Sebelum memulai
dalam panduan ini sebelum mencoba contoh ini.
Anda dapat mencapai interaksi yang lebih cepat dengan tidak menunggu seluruh hasil dari
pembuatan model, dan sebagai gantinya menggunakan streaming untuk menangani hasil sebagian.
Untuk melakukan streaming respons, panggil generateContentStream.
Contoh tampilan: Streaming teks yang dihasilkan dari teks dan satu gambar
Swift
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu gambar:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")guardletimage=UIImage(systemName:"bicycle")else{fatalError()}// Provide a text prompt to include with the imageletprompt="What's in this picture?"// To stream generated text output, call generateContentStream and pass in the promptletcontentStream=trymodel.generateContentStream(image,prompt)fortryawaitchunkincontentStream{iflettext=chunk.text{print(text)}}
Kotlin
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu gambar:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")// Loads an image from the app/res/drawable/ directoryvalbitmap:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky)// Provide a prompt that includes the image specified above and textvalprompt=content{image(bitmap)text("What developer tool is this mascot from?")}// To stream generated text output, call generateContentStream with the promptvarfullResponse=""generativeModel.generateContentStream(prompt).collect{chunk->print(chunk.text)fullResponse+=chunk.text}
Java
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu gambar:
Untuk Java, metode streaming di SDK ini menampilkan
jenis Publisher dari library Reactive Streams.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);Bitmapbitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sparky);// Provide a prompt that includes the image specified above and textContentprompt=newContent.Builder().addImage(bitmap).addText("What developer tool is this mascot from?").build();// To stream generated text output, call generateContentStream with the promptPublisher<GenerateContentResponse>streamingResponse=model.generateContentStream(prompt);finalString[]fullResponse={""};streamingResponse.subscribe(newSubscriber<GenerateContentResponse>(){@OverridepublicvoidonNext(GenerateContentResponsegenerateContentResponse){Stringchunk=generateContentResponse.getText();fullResponse[0]+=chunk;}@OverridepublicvoidonComplete(){System.out.println(fullResponse[0]);}@OverridepublicvoidonError(Throwablet){t.printStackTrace();}@OverridepublicvoidonSubscribe(Subscriptions){}});
Web
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu gambar:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the imageconstprompt="What do you see?";// Prepare image for inputconstfileInputEl=document.querySelector("input[type=file]");constimagePart=awaitfileToGenerativePart(fileInputEl.files[0]);// To stream generated text output, call generateContentStream with the text and imageconstresult=awaitmodel.generateContentStream([prompt,imagePart]);forawait(constchunkofresult.stream){constchunkText=chunk.text();console.log(chunkText);}}run();
Dart
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu gambar:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');// Provide a text prompt to include with the imagefinalprompt=TextPart("What's in the picture?");// Prepare images for inputfinalimage=awaitFile('image0.jpg').readAsBytes();finalimagePart=InlineDataPart('image/jpeg',image);// To stream generated text output, call generateContentStream with the text and imagefinalresponse=awaitmodel.generateContentStream([Content.multi([prompt,imagePart])]);awaitfor(finalchunkinresponse){print(chunk.text);}
Contoh tampilan: Streaming teks yang dihasilkan dari teks dan beberapa gambar
Swift
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan beberapa gambar:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")guardletimage1=UIImage(systemName:"car")else{fatalError()}guardletimage2=UIImage(systemName:"car.2")else{fatalError()}// Provide a text prompt to include with the imagesletprompt="What's different between these pictures?"// To stream generated text output, call generateContentStream and pass in the promptletcontentStream=trymodel.generateContentStream(image1,image2,prompt)fortryawaitchunkincontentStream{iflettext=chunk.text{print(text)}}
Kotlin
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan beberapa gambar:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")// Loads an image from the app/res/drawable/ directoryvalbitmap1:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky)valbitmap2:Bitmap=BitmapFactory.decodeResource(resources,R.drawable.sparky_eats_pizza)// Provide a prompt that includes the images specified above and textvalprompt=content{image(bitmap1)image(bitmap2)text("What's different between these pictures?")}// To stream generated text output, call generateContentStream with the promptvarfullResponse=""generativeModel.generateContentStream(prompt).collect{chunk->print(chunk.text)fullResponse+=chunk.text}
Java
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan beberapa gambar:
Untuk Java, metode streaming di SDK ini menampilkan
jenis Publisher dari library Reactive Streams.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);Bitmapbitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.sparky);Bitmapbitmap2=BitmapFactory.decodeResource(getResources(),R.drawable.sparky_eats_pizza);// Provide a prompt that includes the images specified above and textContentprompt=newContent.Builder().addImage(bitmap1).addImage(bitmap2).addText("What's different between these pictures?").build();// To stream generated text output, call generateContentStream with the promptPublisher<GenerateContentResponse>streamingResponse=model.generateContentStream(prompt);finalString[]fullResponse={""};streamingResponse.subscribe(newSubscriber<GenerateContentResponse>(){@OverridepublicvoidonNext(GenerateContentResponsegenerateContentResponse){Stringchunk=generateContentResponse.getText();fullResponse[0]+=chunk;}@OverridepublicvoidonComplete(){System.out.println(fullResponse[0]);}@OverridepublicvoidonError(Throwablet){t.printStackTrace();}@OverridepublicvoidonSubscribe(Subscriptions){}});
Web
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan beberapa gambar:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the imagesconstprompt="What's different between these pictures?";constfileInputEl=document.querySelector("input[type=file]");constimageParts=awaitPromise.all([...fileInputEl.files].map(fileToGenerativePart));// To stream generated text output, call generateContentStream with the text and imagesconstresult=awaitmodel.generateContentStream([prompt,...imageParts]);forawait(constchunkofresult.stream){constchunkText=chunk.text();console.log(chunkText);}}run();
Dart
Contoh ini menunjukkan cara menggunakan
generateContentStream
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan beberapa gambar:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');final(firstImage,secondImage)=await(File('image0.jpg').readAsBytes(),File('image1.jpg').readAsBytes()).wait;// Provide a text prompt to include with the imagesfinalprompt=TextPart("What's different between these pictures?");// Prepare images for inputfinalimageParts=[InlineDataPart('image/jpeg',firstImage),InlineDataPart('image/jpeg',secondImage),];// To stream generated text output, call generateContentStream with the text and imagesfinalresponse=awaitmodel.generateContentStream([Content.multi([prompt,...imageParts])]);awaitfor(finalchunkinresponse){print(chunk.text);}
Contoh tampilan: Streaming teks yang dihasilkan dari teks dan video
Swift
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu video:
importFirebaseVertexAI// Initialize the Vertex AI serviceletvertex=VertexAI.vertexAI()// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=vertex.generativeModel(modelName:"gemini-2.0-flash")// Provide the video as `Data` with the appropriate MIME typeletvideo=InlineDataPart(data:tryData(contentsOf:videoURL),mimeType:"video/mp4")// Provide a text prompt to include with the videoletprompt="What is in the video?"// To stream generated text output, call generateContentStream with the text and videoletcontentStream=trymodel.generateContentStream(video,prompt)fortryawaitchunkincontentStream{iflettext=chunk.text{print(text)}}
Kotlin
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu video:
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil
dari Cakupan coroutine.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casevalgenerativeModel=Firebase.vertexAI.generativeModel("gemini-2.0-flash")valcontentResolver=applicationContext.contentResolvercontentResolver.openInputStream(videoUri).use{stream->stream?.let{valbytes=stream.readBytes()// Provide a prompt that includes the video specified above and textvalprompt=content{inlineData(bytes,"video/mp4")text("What is in the video?")}// To stream generated text output, call generateContentStream with the promptvarfullResponse=""generativeModel.generateContentStream(prompt).collect{chunk->Log.d(TAG,chunk.text?:"")fullResponse+=chunk.text}}}
Java
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu video:
Untuk Java, metode streaming di SDK ini menampilkan
jenis Publisher dari library Reactive Streams.
// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use caseGenerativeModelgm=FirebaseVertexAI.getInstance().generativeModel("gemini-2.0-flash");GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);ContentResolverresolver=getApplicationContext().getContentResolver();try(InputStreamstream=resolver.openInputStream(videoUri)){FilevideoFile=newFile(newURI(videoUri.toString()));intvideoSize=(int)videoFile.length();byte[]videoBytes=newbyte[videoSize];if(stream!=null){stream.read(videoBytes,0,videoBytes.length);stream.close();// Provide a prompt that includes the video specified above and textContentprompt=newContent.Builder().addInlineData(videoBytes,"video/mp4").addText("What is in the video?").build();// To stream generated text output, call generateContentStream with the promptPublisher<GenerateContentResponse>streamingResponse=model.generateContentStream(prompt);finalString[]fullResponse={""};streamingResponse.subscribe(newSubscriber<GenerateContentResponse>(){@OverridepublicvoidonNext(GenerateContentResponsegenerateContentResponse){Stringchunk=generateContentResponse.getText();fullResponse[0]+=chunk;}@OverridepublicvoidonComplete(){System.out.println(fullResponse[0]);}@OverridepublicvoidonError(Throwablet){t.printStackTrace();}@OverridepublicvoidonSubscribe(Subscriptions){}});}}catch(IOExceptione){e.printStackTrace();}catch(URISyntaxExceptione){e.printStackTrace();}
Web
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu video:
import{initializeApp}from"firebase/app";import{getVertexAI,getGenerativeModel}from"firebase/vertexai";// TODO(developer) Replace the following with your app's Firebase configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Vertex AI serviceconstvertexAI=getVertexAI(firebaseApp);// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(vertexAI,{model:"gemini-2.0-flash"});// Converts a File object to a Part object.asyncfunctionfileToGenerativePart(file){constbase64EncodedDataPromise=newPromise((resolve)=>{constreader=newFileReader();reader.onloadend=()=>resolve(reader.result.split(',')[1]);reader.readAsDataURL(file);});return{inlineData:{data:awaitbase64EncodedDataPromise,mimeType:file.type},};}asyncfunctionrun(){// Provide a text prompt to include with the videoconstprompt="What do you see?";constfileInputEl=document.querySelector("input[type=file]");constvideoPart=awaitfileToGenerativePart(fileInputEl.files[0]);// To stream generated text output, call generateContentStream with the text and videoconstresult=awaitmodel.generateContentStream([prompt,videoPart]);forawait(constchunkofresult.stream){constchunkText=chunk.text();console.log(chunkText);}}run();
Dart
Anda dapat memanggil
generateContentStream()
untuk melakukan streaming teks yang dihasilkan dari permintaan perintah multimodal yang menyertakan teks
dan satu video:
import'package:firebase_vertexai/firebase_vertexai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Vertex AI service and create a `GenerativeModel` instance// Specify a model that supports your use casefinalmodel=FirebaseVertexAI.instance.generativeModel(model:'gemini-2.0-flash');// Provide a text prompt to include with the videofinalprompt=TextPart("What's in the video?");// Prepare video for inputfinalvideo=awaitFile('video0.mp4').readAsBytes();// Provide the video as `Data` with the appropriate mimetypefinalvideoPart=InlineDataPart('video/mp4',video);// To stream generated text output, call generateContentStream with the text and imagefinalresponse=awaitmodel.generateContentStream([Content.multi([prompt,videoPart])]);awaitfor(finalchunkinresponse){print(chunk.text);}
Berbagai opsi untuk memberikan file dalam permintaan
Jenis file yang didukung
Jenis MIME yang didukung dan cara menentukannya
Persyaratan dan praktik terbaik untuk file dan permintaan multimodal
Kamu bisa apa lagi?
Pelajari cara menghitung token
sebelum mengirim perintah panjang ke model.
Siapkan Cloud Storage for Firebase
agar Anda dapat menyertakan file besar dalam permintaan multimodal dan memiliki
solusi yang lebih terkelola untuk menyediakan file dalam perintah.
File dapat mencakup gambar, PDF, video, dan audio.
Mulailah memikirkan persiapan produksi, termasuk
menyiapkan Firebase App Check
untuk melindungi Gemini API dari penyalahgunaan oleh klien yang tidak sah.
Selain itu, pastikan untuk meninjau
checklist produksi.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-05-01 UTC."],[],[]]