כדי לגשת למודלים Gemini Pro ו-Flash, אנחנו ממליצים למפתחי Android להשתמש ב-Gemini Developer API באמצעות Firebase AI Logic. הוא מאפשר לכם להתחיל לעבוד בלי צורך בכרטיס אשראי, ומציע שכבת תמחור חינמית נדיבה. אחרי שתאמתו את השילוב עם בסיס משתמשים קטן, תוכלו להתרחב על ידי מעבר לרמה בתשלום.
תחילת העבודה
לפני שתבצעו אינטראקציה עם Gemini API ישירות מהאפליקציה, תצטרכו לבצע כמה פעולות, כולל היכרות עם ההנחיות והגדרת Firebase והאפליקציה לשימוש ב-SDK.
התנסות בהנחיות
ניסוי עם הנחיות יכול לעזור לכם למצוא את הניסוח, התוכן והפורמט הטובים ביותר לאפליקציה ל-Android. Google AI Studio הוא סביבת פיתוח משולבת (IDE) שבה אפשר ליצור אב טיפוס של הנחיות ולעצב אותן לפי תרחישי השימוש של האפליקציה.
יצירת ההנחיה המתאימה לתרחיש לדוגמה היא יותר אמנות מאשר מדע, ולכן חשוב מאוד לבצע ניסויים. מידע נוסף על הנחיות זמין במסמכי העזרה של Firebase.
כשהנחיה נראית לכם טובה, לוחצים על הלחצן "<>" כדי לקבל קטעי קוד שאפשר להוסיף לקוד שלכם.
הגדרת פרויקט Firebase וקישור האפליקציה ל-Firebase
כשתהיו מוכנים לבצע קריאה ל-API מהאפליקציה, עליכם לפעול לפי ההוראות שמפורטות בקטע 'שלב 1' במדריך לתחילת העבודה עם Firebase AI Logic כדי להגדיר את Firebase ואת ה-SDK באפליקציה.
מוסיפים את יחסי התלות של Gradle
מוסיפים את יחסי התלות הבאים של Gradle למודול האפליקציה:
Kotlin
dependencies {
// ... other androidx dependencies
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.0"))
// Add the dependency for the Firebase AI Logic library When using the BoM,
// you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-ai")
}
Java
dependencies {
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.0"))
// Add the dependency for the Firebase AI Logic library When using the BoM,
// you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-ai")
// 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")
}
איך מפעילים את המודל הגנרטיבי
מתחילים ביצירת מופע של GenerativeModel
וציון שם המודל:
Kotlin
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash")
Java
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
מידע נוסף על המודלים הזמינים לשימוש עם Gemini Developer API אפשר גם לקרוא מידע נוסף על הגדרת הפרמטרים של המודל.
אינטראקציה עם Gemini Developer API מהאפליקציה
אחרי שהגדרתם את Firebase ואת האפליקציה לשימוש ב-SDK, אתם מוכנים לבצע אינטראקציה עם Gemini Developer API מהאפליקציה.
יצירת טקסט
כדי ליצור תשובה בטקסט, קוראים ל-generateContent()
עם ההנחיה.
Kotlin
scope.launch {
val response = model.generateContent("Write a story about a magic backpack.")
}
Java
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
יצירת טקסט מתמונות וממדיה אחרת
אפשר גם ליצור טקסט מהנחיה שכוללת טקסט וגם תמונות או מדיה אחרת. כשקוראים ל-generateContent()
, אפשר להעביר את המדיה כנתונים מוטמעים.
לדוגמה, כדי להשתמש בתמונת bitmap, צריך להשתמש בסוג התוכן image
:
Kotlin
scope.launch {
val response = model.generateContent(
content {
image(bitmap)
text("what is the object in the picture?")
}
)
}
Java
Content content = new Content.Builder()
.addImage(bitmap)
.addText("what is the object in the picture?")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
כדי להעביר קובץ אודיו, צריך להשתמש בסוג התוכן inlineData
:
Kotlin
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "audio/mpeg") // Specify the appropriate audio MIME type
text("Transcribe this audio recording.")
}
val response = model.generateContent(prompt)
}
}
Java
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(audioUri)) {
File audioFile = new File(new URI(audioUri.toString()));
int audioSize = (int) audioFile.length();
byte audioBytes = new byte[audioSize];
if (stream != null) {
stream.read(audioBytes, 0, audioBytes.length);
stream.close();
// Provide a prompt that includes audio specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(audioBytes, "audio/mpeg") // Specify the appropriate audio MIME type
.addText("Transcribe what's said in this audio recording.")
.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 text = result.getText();
Log.d(TAG, (text == null) ? "" : text);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Failed to generate a response", t);
}
}, executor);
} else {
Log.e(TAG, "Error getting input stream for file.");
// Handle the error appropriately
}
} catch (IOException e) {
Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
Log.e(TAG, "Invalid audio file", e);
}
כדי לספק קובץ וידאו, ממשיכים להשתמש בסוג התוכן inlineData
:
Kotlin
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "video/mp4") // Specify the appropriate video MIME type
text("Describe the content of this video")
}
val response = model.generateContent(prompt)
}
}
Java
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 video specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("Describe the content of this 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();
}
באופן דומה, אפשר גם להעביר מסמכי PDF (application/pdf
) ומסמכי טקסט פשוט (text/plain
) על ידי העברת סוג ה-MIME המתאים שלהם כפרמטר.
שיחה עם זיכרון
אפשר גם לתמוך בשיחות עם כמה תורנים. מפעילים צ'אט באמצעות הפונקציה startChat()
. אפשר גם לספק למודל היסטוריית הודעות. לאחר מכן, קוראים לפונקציה sendMessage()
כדי לשלוח הודעות בצ'אט.
Kotlin
val chat = model.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?") }
)
)
scope.launch {
val response = chat.sendMessage("How many paws are in my house?")
}
Java
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 messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");
Content message = messageBuilder.build();
// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
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);
פרטים נוספים זמינים במסמכי התיעוד של Firebase.
השלבים הבאים
- מומלץ לעיין באפליקציה לדוגמה של Firebase למתחילים ב-Android ובקטלוג הדוגמאות של AI ל-Android ב-GitHub.
- הכנת האפליקציה לסביבת הייצור, כולל הגדרת Firebase App Check כדי להגן על Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים.
- מידע נוסף על Firebase AI Logic זמין במסמכי העזרה של Firebase.