หากคุณเพิ่งเริ่มใช้ Gemini API Gemini Developer API คือผู้ให้บริการ API ที่แนะนําสําหรับนักพัฒนาแอป Android แต่หากมีข้อกําหนดตําแหน่งข้อมูลเฉพาะหรือฝังอยู่ในสภาพแวดล้อม Vertex AI หรือ Google Cloud อยู่แล้ว คุณจะใช้ Vertex AI Gemini API ได้
การย้ายข้อมูลจาก Vertex AI ใน Firebase
หากก่อนหน้านี้คุณผสานรวมโมเดล Gemini Flash และ Pro โดยใช้ Vertex AI ใน Firebase คุณสามารถย้ายข้อมูลและใช้ Vertex AI ในฐานะผู้ให้บริการ API ต่อได้ อ่านคําแนะนําในการย้ายข้อมูลโดยละเอียดในเอกสารประกอบของ Firebase
เริ่มต้นใช้งาน
คุณสามารถทดสอบพรอมต์ใน Vertex AI Studio ก่อนที่จะโต้ตอบกับ Vertex AI Gemini API จากแอปโดยตรง
ตั้งค่าโปรเจ็กต์ Firebase และเชื่อมต่อแอปกับ Firebase
เมื่อพร้อมเรียกใช้ Vertex AI Gemini API จากแอปแล้ว ให้ทําตามวิธีการในคู่มือเริ่มต้นใช้งาน Firebase AI Logic "ขั้นตอนที่ 1" เพื่อตั้งค่า Firebase และ SDK ในแอป
เพิ่มการพึ่งพา Gradle
เพิ่ม Dependency ของ Gradle ต่อไปนี้ลงในโมดูลแอป
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")
}
เริ่มต้นโมเดล Generative
เริ่มต้นด้วยการสร้างอินสแตนซ์ GenerativeModel
และระบุชื่อโมเดล
Kotlin
val model = Firebase.ai(backend = GenerativeBackend.vertexAI())
.generativeModel("gemini-2.0-flash")
Java
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.vertexAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
ดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบที่ใช้ได้สำหรับใช้กับ Gemini Developer API ได้ในเอกสารประกอบของ Firebase นอกจากนี้ คุณยังดูข้อมูลเกี่ยวกับการกำหนดค่าพารามิเตอร์ของโมเดลได้ด้วย
สร้างข้อความ
หากต้องการสร้างคำตอบที่เป็นข้อความ ให้เรียกใช้ generateContent()
พร้อมพรอมต์
Kotlin
kotlin
// Note: generateContent() is a suspend function, which integrates well
// with existing Kotlin code.
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);
คุณสามารถส่งรูปภาพ เสียง วิดีโอ และไฟล์พร้อมกับพรอมต์ข้อความได้เช่นเดียวกับ Gemini Developer API (ดู "โต้ตอบกับ Gemini Developer API จากแอปของคุณ")
ดูข้อมูลเพิ่มเติมเกี่ยวกับ Firebase AI Logic SDK ได้ในเอกสารประกอบของ Firebase