מדריך: תחילת העבודה עם Gemini API


במדריך הזה נדגים איך לגשת ל-Gemini API ישירות מהאפליקציה ל-Android באמצעות ה-SDK של הלקוח שמבוסס על AI מבית Google ל-Android. אם אתם לא רוצים לעבוד ישירות עם ממשקי API ל-REST או עם קוד בצד השרת (כמו Python) כדי לגשת למודלים של Gemini באפליקציה ל-Android, אתם יכולים להשתמש ב-SDK של הלקוח הזה.

במדריך הזה תלמדו איך לבצע את הפעולות הבאות:

בנוסף, המדריך כולל קטעים על תרחישים מתקדמים לדוגמה (כמו ספירת אסימונים) ואפשרויות לשליטה ביצירת תוכן.

כדאי לגשת ל-Gemini במכשיר

ערכת ה-SDK של הלקוח ל-Android שמתוארת במדריך הזה מאפשרת לכם לגשת למודלים של Gemini Pro שפועלים בשרתים של Google. בתרחישים לדוגמה שקשורים לעיבוד מידע אישי רגיש, לזמינות ללא חיבור לאינטרנט או לחיסכון בעלויות של תהליכי העבודה של המשתמשים בתדירות גבוהה, כדאי לשקול את הגישה ל-Gemini Nano שפועל במכשיר. מידע נוסף זמין במדריך Android (במכשיר).

דרישות מוקדמות

המדריך הזה מניח שאתם מכירים את השימוש ב-Android Studio לפיתוח אפליקציות ל-Android.

כדי להשלים את המדריך הזה, ודאו שסביבת הפיתוח והאפליקציה ל-Android עומדות בדרישות הבאות:

  • Android Studio (הגרסה האחרונה)
  • האפליקציה ל-Android חייבת לטרגט לרמת API 21 ומעלה.

הגדרת הפרויקט

לפני שליחת קריאה ל-Gemini API, צריך להגדיר את הפרויקט ל-Android, שכולל הגדרה של מפתח ה-API, הוספת יחסי תלות של ה-SDK לפרויקט ב-Android והפעלת המודל.

הגדרה של מפתח API

כדי להשתמש ב-Gemini API, צריך מפתח API. אם עדיין אין לכם מפתח, צרו מפתח ב-Google AI Studio.

קבלת מפתח API

אבטחה של מפתח ה-API

מומלץ מאוד לא לבדוק מפתח API במערכת לניהול גרסאות. במקום זאת, צריך לאחסן אותו בקובץ local.properties (ממוקם בספריית השורש של הפרויקט, אבל לא נכלל בניהול הגרסאות), ולאחר מכן להשתמש בפלאגין של Secrets Gradle ל-Android כדי לקרוא את מפתח ה-API כמשתנה Build Configuration.

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;

כל קטעי הקוד במדריך הזה מבוססים על השיטה המומלצת הזו. בנוסף, אם אתם רוצים לראות את ההטמעה של הפלאגין Secrets Gradle, תוכלו לעיין באפליקציה לדוגמה לערכת ה-SDK הזו או להשתמש בגרסה העדכנית ביותר של Android Studio Iguana שיש בה תבנית Gemini API Starter (שכוללת את הקובץ local.properties כדי לעזור לכם להתחיל).

הוספת התלות של ה-SDK לפרויקט

  1. במודול (ברמת האפליקציה) של קובץ התצורה של Gradle (למשל <project>/<app-module>/build.gradle.kts), מוסיפים את התלות של ה-SDK של Google AI ל-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.9.0")
    }
    

    Java

    ב-Java, צריך להוסיף עוד שתי ספריות.

    dependencies {
        // ... other androidx dependencies
    
        // add the dependency for the Google AI client SDK for Android
        implementation("com.google.ai.client.generativeai:generativeai:0.9.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. סנכרון פרויקט Android עם קובצי Gradle.

אתחול המודל הגנרטיבי

לפני שתוכלו לבצע קריאות ל-API, תצטרכו לאתחל את המודל הגנרטיבי:

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

ב-Java, צריך גם לאתחל את האובייקט 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);

כשמציינים מודל, חשוב לשים לב לנקודות הבאות:

  • כדאי להשתמש במודל ספציפי לתרחיש לדוגמה שלכם (לדוגמה, gemini-1.5-flash מיועד לקלט מרובה מצבים). במדריך הזה מופיעות ההוראות לכל הטמעה, יחד עם רשימת המודל המומלץ לכל תרחיש לדוגמה.

הטמעת תרחישים נפוצים לדוגמה

אחרי שהפרויקט מוגדר, אתם יכולים להשתמש ב-Gemini API כדי להטמיע תרחישים לדוגמה שונים:

יצירת טקסט מקלט טקסט בלבד

כשהקלט של ההנחיה כולל רק טקסט, צריך להשתמש במודל Gemini 1.5 או במודל Gemini 1.0 Pro עם generateContent כדי ליצור פלט טקסט:

Kotlin

שימו לב ש-generateContent() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

הערה: generateContent() מחזירה ListenableFuture. אם אתם לא מכירים את ה-API הזה, תוכלו להיעזר במאמרי העזרה של Android בנושא שימוש ב-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);

יצירת טקסט מקלט טקסט ותמונה (multimodal)

ב-Gemini יש כמה מודלים שיכולים לטפל בקלט מרובה מצבים (מודלים של Gemini 1.5) כדי להזין גם טקסט וגם תמונות. חשוב לבדוק את הדרישות לתמונות בנוגע להנחיות.

כשהקלט של ההנחיה כולל גם טקסט וגם תמונות, משתמשים במודל Gemini 1.5 עם generateContent כדי ליצור פלט טקסט:

Kotlin

שימו לב ש-generateContent() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

הערה: generateContent() מחזירה ListenableFuture. אם אתם לא מכירים את ה-API הזה, תוכלו להיעזר במאמרי העזרה של Android בנושא שימוש ב-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);

יצירת שיחות עם ריבוי פניות (צ'אט)

בעזרת Gemini אפשר ליצור שיחות בפריסה גמישה בכמה תורות. ה-SDK מפשט את התהליך בכך שהוא מנהל את מצב השיחה, כך שבניגוד ל-generateContent, לא צריך לאחסן את היסטוריית השיחות בעצמכם.

כדי ליצור שיחה במספר תורות (כמו צ'אט), צריך להשתמש במודל Gemini 1.5 או מודל Gemini 1.0 Pro, ולהתחיל את השיחה דרך startChat(). לאחר מכן משתמשים ב-sendMessage() כדי לשלוח הודעה חדשה למשתמש, והפעולה הזו תגרום גם לצירוף של ההודעה ושל התשובה להיסטוריית הצ'אט.

יש שתי דרכים אפשריות לשייך את role לתוכן בשיחה:

  • user: התפקיד שמספק את ההנחיות. הערך הזה הוא ברירת המחדל לקריאות ל-sendMessage.

  • model: התפקיד שמספק את התשובות. אפשר להשתמש בתפקיד הזה כשקוראים לפונקציה startChat() עם history קיים.

Kotlin

שימו לב ש-generateContent() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

הערה: generateContent() מחזירה ListenableFuture. אם אתם לא מכירים את ה-API הזה, תוכלו להיעזר במאמרי העזרה של Android בנושא שימוש ב-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);

שימוש בסטרימינג לאינטראקציות מהירות יותר

כברירת מחדל, המודל מחזיר תשובה אחרי כל תהליך היצירה. אפשר להשיג אינטראקציות מהר יותר אם לא מחכים לתוצאה כולה, ובמקום זאת משתמשים בסטרימינג כדי לטפל בתוצאות חלקיות.

הדוגמה הבאה ממחישה איך להטמיע סטרימינג עם generateContentStream כדי ליצור טקסט מהנחיה של טקסט ותמונה.

Kotlin

שימו לב ש-generateContentStream() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

ה-methods של Java בסטרימינג ב-SDK הזה מחזירות סוג Publisher מהספרייה של Reactive Streams.

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

אפשר להשתמש בשיטה דומה לקלט של טקסט בלבד ולשימוש בצ'אט:

Kotlin

שימו לב ש-generateContentStream() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

ה-methods של Java בסטרימינג ב-SDK הזה מחזירות סוג Publisher מהספרייה של Reactive Streams.

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

הטמעת תרחישים מתקדמים לדוגמה

התרחישים הנפוצים לדוגמה שמתוארים בקטע הקודם במדריך הזה יעזרו לכם להתרגל לשימוש ב-Gemini API. בקטע הזה מתוארים כמה תרחישים לדוגמה שעשויים להיחשב למתקדמים יותר.

שליחת פונקציות

שליחת פונקציות מאפשרת לקבל בקלות פלט של נתונים מובְנים ממודלים גנרטיביים. לאחר מכן אפשר להשתמש בפלט הזה כדי לקרוא לממשקי API אחרים ולהחזיר למודל את נתוני התגובות הרלוונטיים. כלומר, קריאה לפונקציות עוזרת לחבר מודלים גנרטיביים למערכות חיצוניות, כדי שהתוכן שנוצר יכלול את המידע הכי עדכני ומדויק. מידע נוסף מופיע במדריך להפעלת פונקציות.

ספירת אסימונים

כשמשתמשים בהנחיות ארוכות, כדאי לספור אסימונים לפני ששולחים תוכן למודל. הדוגמאות הבאות מראות איך להשתמש ב-countTokens() לתרחישים שונים לדוגמה:

Kotlin

שימו לב ש-countTokens() היא פונקציית השעיה וצריך לקרוא לה מהיקף של Coroutine. אם אתם לא מכירים את Coroutines, תוכלו לקרוא את המאמר Kotlin Coroutines ב-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

הערה: countTokens() מחזירה ListenableFuture. אם אתם לא מכירים את ה-API הזה, תוכלו להיעזר במאמרי העזרה של Android בנושא שימוש ב-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]));

אפשרויות להגדרת יצירת תוכן

אפשר לשלוט ביצירת התוכן על ידי הגדרת הפרמטרים של המודל ובאמצעות שימוש בהגדרות הבטיחות.

הגדרת פרמטרים של מודל

כל הנחיה ששולחים למודל כוללת ערכי פרמטרים שקובעים איך המודל יוצר תשובה. המודל יכול ליצור תוצאות שונות לערכי פרמטרים שונים. מידע נוסף על פרמטרים של מודלים

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

שימוש בהגדרות בטיחות

אפשר להשתמש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תגובות שעלולות להיחשב מזיקות. כברירת מחדל, הגדרות הבטיחות חוסמות תוכן עם סבירות בינונית ו/או גבוהה להיות תוכן לא בטוח בכל המימדים. מידע נוסף על הגדרות בטיחות

כך קובעים הגדרת בטיחות אחת:

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

אפשר גם לקבוע יותר מהגדרת בטיחות אחת:

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

מה עושים אחר כך

  • עיצוב הנחיות הוא התהליך של יצירת הנחיות שמעוררים את התשובה הרצויה ממודלים של שפה. חשוב לכתוב הנחיות עם מבנה נכון כדי להבטיח תשובות מדויקות ואיכותיות ממודל השפה. שיטות מומלצות לכתיבה של הנחיות

  • Gemini מציע כמה וריאציות של מודלים כדי לענות על הצרכים של תרחישי שימוש שונים, כמו סוגי הקלט ומורכבות, הטמעות ל-Chat או למשימות שפה אחרות עם דיאלוגים והגבלות גודל. מידע על המודלים הזמינים של Gemini

  • ערכת ה-SDK של הלקוח ל-Android שמתוארת במדריך הזה מאפשרת לכם לגשת למודלים של Gemini Pro שפועלים בשרתים של Google. בתרחישים לדוגמה שקשורים לעיבוד מידע אישי רגיש, לזמינות ללא חיבור לאינטרנט או לחיסכון בעלויות של תהליכי העבודה של המשתמשים בתדירות גבוהה, כדאי לשקול את הגישה ל-Gemini Nano שפועל במכשיר. מידע נוסף זמין במדריך Android (במכשיר).