หากคุณยังไม่เคยใช้ 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 Gemini API โดยตรงจากแอป คุณ สามารถทดลองใช้พรอมต์ใน Vertex AI Studio ได้
ตั้งค่าโปรเจ็กต์ Firebase และเชื่อมต่อแอปกับ Firebase
เมื่อพร้อมที่จะเรียก Vertex AI Gemini API จากแอปแล้ว ให้ทำตามวิธีการในคู่มือเริ่มต้นใช้งาน Firebase AI Logic ในส่วน "ขั้นตอนที่ 1" เพื่อตั้งค่า Firebase และ SDK ในแอป
เพิ่มทรัพยากร Dependency ของ Gradle
เพิ่มทรัพยากร Dependency ของ Gradle ต่อไปนี้ลงในโมดูลแอป
dependencies {
// ... other androidx dependencies
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:34.12.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.5-flash")
Java
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.vertexAI()) .generativeModel("gemini-2.5-flash"); GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
ในเอกสารประกอบของ Firebase คุณสามารถดูข้อมูลเพิ่มเติมเกี่ยวกับโมเดล ที่พร้อมใช้งานเพื่อใช้กับ Gemini Developer API รวมถึงดูข้อมูลเกี่ยวกับการกำหนดค่าพารามิเตอร์ของโมเดล เกี่ยวกับ การกำหนดค่าพารามิเตอร์ของโมเดล
สร้างข้อความ
หากต้องการสร้างการตอบกลับเป็นข้อความ ให้เรียก generateContent() ด้วยพรอมต์
Kotlin
suspend fun generateText(model: GenerativeModel) { // Note: generateContent() is a suspend function, which integrates well // with existing Kotlin code. 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