หากต้องการเข้าถึงโมเดล Gemini Pro และ Flash เราขอแนะนำให้นักพัฒนาแอป Android ใช้ Gemini Developer API โดยใช้ตรรกะ AI ของ Firebase ซึ่งจะช่วยให้คุณเริ่มต้นใช้งานได้โดยไม่ต้องใช้บัตรเครดิต และมีแพ็กเกจแบบไม่มีค่าใช้จ่ายที่คุ้มค่า เมื่อตรวจสอบการผสานรวมกับฐานผู้ใช้กลุ่มเล็กๆ แล้ว คุณจะปรับขนาดได้โดยเปลี่ยนไปใช้แพ็กเกจแบบชำระเงิน
เริ่มต้นใช้งาน
ก่อนที่จะโต้ตอบกับ Gemini API จากแอปโดยตรง คุณจะต้องทําสิ่งต่างๆ 2-3 อย่างก่อน ซึ่งรวมถึงทำความคุ้นเคยกับการแจ้งเตือน รวมถึงการตั้งค่า Firebase และแอปเพื่อใช้ SDK
ทดลองใช้พรอมต์
การทดสอบพรอมต์จะช่วยให้คุณพบวลี เนื้อหา และรูปแบบที่ดีที่สุดสําหรับแอป Android Google AI Studio เป็น IDE ที่คุณสามารถใช้ในการสร้างต้นแบบและออกแบบพรอมต์สําหรับ Use Case ของแอป
การสร้างพรอมต์ที่เหมาะสมสำหรับ Use Case ของคุณเป็นศิลปะมากกว่าวิทยาศาสตร์ ซึ่งทำให้การทดสอบมีความสําคัญ ดูข้อมูลเพิ่มเติมเกี่ยวกับการแจ้งได้ในเอกสารประกอบของ Firebase
เมื่อพอใจกับพรอมต์แล้ว ให้คลิกปุ่ม "<>" เพื่อดูข้อมูลโค้ดที่เพิ่มลงในโค้ดได้
ตั้งค่าโปรเจ็กต์ Firebase และเชื่อมต่อแอปกับ Firebase
เมื่อพร้อมเรียก API จากแอปแล้ว ให้ทําตามวิธีการใน "ขั้นตอนที่ 1" ของคู่มือเริ่มต้นใช้งาน Firebase AI Logic เพื่อตั้งค่า Firebase และ SDK ในแอป
เพิ่มการพึ่งพา Gradle
เพิ่ม Dependency ของ 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")
}
เริ่มต้นโมเดล Generative
เริ่มต้นด้วยการสร้างอินสแตนซ์ 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()
คุณสามารถส่งสื่อเป็นข้อมูลในบรรทัด
เช่น หากต้องการใช้บิตแมป ให้ใช้ประเภทเนื้อหา 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 จากการละเมิดโดยไคลเอ็นต์ที่ไม่ได้รับอนุญาต
- ดูข้อมูลเพิ่มเติมเกี่ยวกับตรรกะ AI ของ Firebase ในเอกสารประกอบของ Firebase