Gemini Pro 및 Flash 모델에 액세스하려면 Android 개발자는 Firebase AI 로직을 사용하여 Gemini Developer API를 사용하는 것이 좋습니다. 신용카드 없이도 시작할 수 있으며 넉넉한 무료 등급을 제공합니다. 소규모 사용자층을 대상으로 통합을 검증한 후 유료 등급으로 전환하여 확장할 수 있습니다.
시작하기
앱에서 Gemini API와 직접 상호작용하기 전에 메시지 표시를 숙지하고 SDK를 사용하도록 Firebase와 앱을 설정하는 등 몇 가지 작업을 먼저 해야 합니다.
프롬프트 실험
프롬프트를 실험하면 Android 앱에 가장 적합한 문구, 콘텐츠, 형식을 찾는 데 도움이 됩니다. Google AI 스튜디오는 앱의 사용 사례에 맞는 프롬프트의 프로토타입을 제작하고 디자인하는 데 사용할 수 있는 IDE입니다.
사용 사례에 적합한 프롬프트를 만드는 것은 과학보다는 기술에 가깝기 때문에 실험이 중요합니다. 프롬프트에 관한 자세한 내용은 Firebase 문서를 참고하세요.
프롬프트가 마음에 들면 '<>" 버튼을 클릭하여 코드에 추가할 수 있는 코드 스니펫을 가져옵니다.
Firebase 프로젝트 설정 및 앱을 Firebase에 연결
앱에서 API를 호출할 준비가 되면 Firebase AI 로직 시작 가이드의 '1단계'에 나온 안내에 따라 앱에서 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")
}
자바
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")
자바
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
Gemini Developer API와 함께 사용할 수 있는 모델에 대해 자세히 알아보세요. 모델 매개변수 구성에 대해 자세히 알아볼 수도 있습니다.
앱에서 Gemini Developer API와 상호작용
이제 SDK를 사용하도록 Firebase와 앱을 설정했으므로 앱에서 Gemini Developer API와 상호작용할 수 있습니다.
텍스트 생성
텍스트 응답을 생성하려면 프롬프트와 함께 generateContent()
를 호출합니다.
Kotlin
scope.launch {
val response = model.generateContent("Write a story about a magic backpack.")
}
자바
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()
를 호출할 때 미디어를 인라인 데이터로 전달할 수 있습니다.
예를 들어 비트맵을 사용하려면 image
콘텐츠 유형을 사용하세요.
Kotlin
scope.launch {
val response = model.generateContent(
content {
image(bitmap)
text("what is the object in the picture?")
}
)
}
자바
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)
}
}
자바
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)
}
}
자바
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?")
}
자바
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 문서를 참고하세요.
다음 단계
- GitHub에서 Android 빠른 시작 Firebase 샘플 앱 및 Android AI 샘플 카탈로그를 검토합니다.
- 승인되지 않은 클라이언트의 악용으로부터 Gemini API를 보호하기 위해 Firebase 앱 체크를 설정하는 등 프로덕션용 앱을 준비합니다.
- Firebase 문서에서 Firebase AI 로직에 대해 자세히 알아보세요.