Gemini modelinden, yalnızca metin içeren bir istemden veya çok formatlı bir istemden metin üretmesini isteyebilirsiniz. Firebase AI Logic kullandığınızda bu isteği doğrudan uygulamanızdan gönderebilirsiniz.
Çok formatlı istem yazma, birden fazla giriş türü (ör. resim, PDF, düz metin dosyası, ses ve video ile birlikte metin) içerebilir.
Bu kılavuzda, yalnızca metin içeren bir istemden ve dosya içeren temel bir çok formatlı istemden nasıl metin oluşturulacağı gösterilmektedir.
Yalnızca metin girişi için koda atla Çok formatlı giriş için koda atla Akış yanıtları için koda atla
|
Metinle çalışmayla ilgili diğer seçenekler için diğer kılavuzlara göz atın Yapılandırılmış çıkış oluşturma Çok turlu sohbet Cihaz üzerinde metin oluşturma Metin okuma (TTS) Metinden görüntü oluşturma |
Başlamadan önce
|
Bu sayfada sağlayıcıya özel içerikleri ve kodları görüntülemek için Gemini API sağlayıcınızı tıklayın. |
Henüz yapmadıysanız başlangıç kılavuzundaki adımları tamamlayın. Bu kılavuzda Firebase projenizi nasıl oluşturacağınız, uygulamanızı Firebase'e nasıl bağlayacağınız, SDK'yı nasıl ekleyeceğiniz, seçtiğiniz Gemini API sağlayıcı için arka uç hizmetini nasıl başlatacağınız ve bir GenerativeModel örneği nasıl oluşturacağınız açıklanmaktadır.
İstemlerinizi test etmek ve yinelemek için Google AI Studio kullanmanızı öneririz.
Yalnızca metin içeren girişten metin oluşturma
|
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu bölümde, seçtiğiniz Gemini API sağlayıcıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
Yalnızca metin girişiyle istem vererek Gemini modelinden metin üretmesini isteyebilirsiniz.
Swift
Yalnızca metin içeren girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.8-flash")
// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
Yalnızca metin içeren girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-3.8-flash")
// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
val response = model.generateContent(prompt)
print(response.text)
Java
Yalnızca metin içeren girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
ListenableFuture döndürür.
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.8-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a prompt that contains text
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
// To generate text output, call generateContent with the text input
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);
Web
Yalnızca metin içeren girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(ai, { model: "gemini-3.8-flash" });
// Wrap in an async function so you can use await
async function run() {
// Provide a prompt that contains text
const prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
const result = await model.generateContent(prompt);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
Yalnızca metin girişinden metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-3.8-flash');
// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];
// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);
Unity
Yalnızca metin içeren girişten metin oluşturmak için GenerateContentAsync() yöntemini çağırabilirsiniz.
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.8-flash");
// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";
// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
Metin ve dosya (çok formatlı) girişinden metin oluşturma
|
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu bölümde, seçtiğiniz Gemini API sağlayıcıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
Gemini modelinden, metin ve dosya içeren bir istemle metin üretmesini isteyebilirsiniz. Bunun için her giriş dosyasının mimeType değerini ve dosyanın kendisini sağlamanız gerekir. Giriş dosyalarıyla ilgili koşulları ve önerileri bu sayfanın ilerleyen bölümlerinde bulabilirsiniz.
Aşağıdaki örnekte, satır içi veri (base64 olarak kodlanmış dosya) olarak sağlanan tek bir video dosyasını analiz ederek dosya girişinden metin oluşturmanın temel adımları gösterilmektedir.
Bu örnekte dosyanın satır içi olarak sağlandığı gösterilmektedir ancak SDK'lar YouTube URL'si sağlamayı da destekler.
Swift
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.8-flash")
// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")
// Provide a text prompt to include with the video
let prompt = "What is in the video?"
// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")
Kotlin
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-3.8-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 = model.generateContent(prompt)
Log.d(TAG, response.text ?: "")
}
}
Java
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
ListenableFuture döndürür.
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.8-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
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();
}
Web
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(ai, { model: "gemini-3.8-flash" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
type: "inlineData",
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt to include with the video
const prompt = "What do you see?";
const fileInputEl = document.querySelector("input[type=file]");
const videoPart = await fileToGenerativePart(fileInputEl.files[0]);
// To generate text output, call generateContent with the text and video
const result = await model.generateContent([prompt, videoPart]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için generateContent() yöntemini çağırabilirsiniz.
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-3.8-flash');
// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");
// Prepare video for input
final video = await File('video0.mp4').readAsBytes();
// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);
// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
Content.multi([prompt, videoPart])
]);
print(response.text);
Unity
Metin ve video dosyalarından oluşan çok formatlı girişten metin oluşturmak için GenerateContentAsync() yöntemini çağırabilirsiniz.
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.8-flash");
// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));
// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");
// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
Yanıtı akış şeklinde göster
|
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu bölümde, seçtiğiniz Gemini API sağlayıcıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
Model tarafından üretilen sonucun tamamını beklemek yerine akış özelliğini kullanarak kısmi sonuçları işleyebilir ve daha hızlı etkileşimler elde edebilirsiniz.
Yanıtı aktarmak için generateContentStream yöntemini çağırın.
Giriş resim dosyaları için koşullar ve öneriler
Satır içi veri olarak sağlanan bir dosyanın aktarım sırasında base64 olarak kodlandığını ve bunun da isteğin boyutunu artırdığını unutmayın. İstek çok büyükse HTTP 413 hatası alırsınız.
Aşağıdakiler hakkında ayrıntılı bilgi edinmek için Agent Platform Gemini API (formerly Vertex AI) için desteklenen giriş dosyaları ve koşullar başlıklı makaleyi inceleyin:
- İstekte dosya sağlamak için farklı seçenekler (satır içi olarak veya dosyanın URL'sini ya da URI'sini kullanarak)
- Desteklenen dosya türleri
- Desteklenen MIME türleri ve bunları belirtme yöntemi
- Dosyalar ve çok formatlı istekler için koşullar ve en iyi uygulamalar
Başka ne yapabilirsin?
- Modele uzun istemler göndermeden önce parçaları nasıl sayacağınızı öğrenin.
- Cloud Storage for Firebase kurulumu büyük dosyaları çok formatlı isteklerinize dahil edebilmenizi ve istemlerde dosya sağlamak için daha yönetilebilir bir çözüme sahip olmanızı sağlar. Dosyalar resim, PDF, video ve ses içerebilir.
-
Üretime hazırlanmaya başlayın (üretim yapılacaklar listesine bakın):
- Gemini API hizmetini yetkisiz istemcilerin kötüye kullanımından korumak için Firebase App Check politikasını mümkün olan en kısa sürede uygulayın.
- Uygulamanızın yeni bir sürümünü yayınlamadan yapay zeka özelliğinizin yapılandırmalarında (model adı gibi) seç-izle değişiklikler yapabilmek için Firebase Remote Config veya sunucu istem şablonlarını kullanın.
Diğer özellikleri deneme
- Çok adımlı görüşmeler (sohbet) oluşturun.
- Yalnızca metin içeren istemlerden metin oluşturma
- Hem metin hem de çok formatlı istemlerden yapılandırılmış çıkış (ör. JSON) oluşturun.
- Hem metin hem de çok formatlı istem yazmadan görüntü oluşturun ve düzenleyin.
- Gemini metin okuma (TTS) modellerini kullanarak konuşma (hem tek hem de birden fazla konuşmacı) oluşturun.
- Gemini Live API kullanarak giriş ve çıkışı (ses dahil) aktarın.
-
Gemini modelini uygulamanızın diğer bölümlerine, harici sistemlere ve bilgilere bağlamak için araçları (işlev çağrısı ve
Google Search veyaGoogle Maps ile temellendirme gibi) kullanın.
İçerik üretimini nasıl kontrol edeceğinizi öğrenin.
- En iyi uygulamalar, stratejiler ve örnek istemler de dahil olmak üzere istem tasarımını anlama
- Maksimum çıkış jetonu sayısı, tekrarlanan çıkış jetonlarının olasılığı gibi model parametrelerini yapılandırın.
- Zararlı olarak değerlendirilebilecek yanıtlar alma olasılığını ayarlamak için güvenlik ayarlarını kullanın.
Desteklenen modeller hakkında daha fazla bilgi
Çeşitli kullanım alanları için kullanılabilen modeller, kotaları ve fiyatlandırmaları hakkında bilgi edinin.Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirimde bulunun